I am adding a logger to my program, surfing the net I add to my code a very simple logger with the basic 2-line definition:
private static final Logger LOG = Logger.getLogger(GUI.class.getName());
public MyClass(){
//other stuff...
LOG.info("text to log");
//other stuff...
}
After few hours of developing I was wondering how to format the style of the logged text and I came to this class:
java.util.logging.SimpleFormatter
Reading the Javadoc I can find:
The formatting can be customized by specifying the format string in the java.util.logging.SimpleFormatter.format property.
There are also few examples:
Some example formats:
java.util.logging.SimpleFormatter.format="%4$s: %5$s [%1$tc]%n"
This prints 1 line with the log level (4$), the log message (5$) and the timestamp (1$) in a square bracket.
WARNING: warning message [Tue Mar 22 13:11:31 PDT 2011]
I tried each one of them, but the “format” field is “not visible” (private I suppose) so I can’t edit it directly. There isn’t any method similar to
setStringVar(String regex);
to set the var from the outside.
I tried to extends the class
public class MyClass extends SimpleFormatter{
but “format” var is not editable. I also tried extending Formatter (the super-class of SimpleFormatter) without success.
The only thing I could do is to extend SimpleFormatter and manually override its:
public String format(LogRecord rec);
with boring and complicated code.
I was just wondering if is there any way to simply use the inside regex reader of the SimpleFormatter Class
EDIT:errors
Have you looked at the JavaDoc. It gives a overview of the SimpleFormatter.
Also, format is a public method within SimpleFormatter.
Further the line
should be defined in a properties file and not the Java class.
To be honest, I don’t use java.util.logging I use log4j as Fildor mentioned. I find it much simpler. First you need a config file, like log4j.xml below:
You are free to tweak the conversion pattern, see PatternLayout for details. Then in your class define the following private static member
The simply when you want to output logging do: