Reputation: 143
Im working on a Logger for services with different elements.
My example for this:
public abstract class Service{
String name = "";
String uId = "";
int counter = 0;
Logger logger = new Logger();
public void info(String message) {
logger.info(this, message);
}
}
public class ServiceA extends Service{
public ServiceA() {
this.name = ...;
this.uId = ...;
this.counter = ...;
}
}
The idea would be that the logger would be called with the service and the message to be logged, in this case as an info. The Logger would then log down the informations of the service with a certain format. Something like this.
[INFO] Timestamp - name (uId) #counter: message
Where Timestamp is the current time, name, uId, counter and message would be given by the method call.
The simple idea would be to have this as a fixed format, so that the string would always look the same. For that i could use String.format.
public class Logger {
public void info(Service service, String message){
String loggingMessage = String.format("[INFO] %s - %s (%s) #%d: %s", timer.getTs(), service.name,
service.uId, service.counter, message);
logMessage(loggingMessage);
}
}
Is there a way to define a sort of custom formatter, that allows me to use my service class like it is one argument instead of the 3 variables in it? Sort of the calender example given in this java documentation.
Calendar c = new GregorianCalendar(1995, MAY, 23);
String s = String.format("Duke's Birthday: %1$tb %1$te, %1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"
That way i could just define a format String, what the logging output should look like instead of a rigid defined string with several arguments from the same referenced instance.
Or is there another way to define a format for my logging output?
Upvotes: 0
Views: 41