Java Standard Logging
This article describes a template for using and configuring logging in a Java application. Even without any configuration we obtain a logger by calling the static method Logger.getLogger(String name). By convention, I use the class name of the class whose member the logger is as name:
this.log = Logger.getLogger(this.getClass().getName());
The default logging behavior is to log all events to standard error, however we can easily redirect/mirror our logging to a log file. The necessary configuration is outsourced in a properties file (often called logging.properties, Download):
# Determine which of the handlers configured below shall be used
handlers= java.util.logging.ConsoleHandler, java.util.logging.FileHandler
# One log entry looks as follows:
#
# May 8, 2013 11:18:47 AM de.svenlogan.wordpress.logging.Application run
# INFO: This message goes to standard error and to the logfile
#
java.util.logging.SimpleFormatter.format="%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%n"
# Only log events of at least level INFO (incl. WARNING, SEVERE,...)
java.util.logging.ConsoleHandler.level=INFO
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
# Log anything
java.util.logging.FileHandler.level=ALL
java.util.logging.FileHandler.pattern=logfile.txt
java.util.logging.FileHandler.append=true
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
In order to make this configuration file knwon to our application, we need to request the LogManager to read the configuration file:
try
{
LogManager.getLogManager().readConfiguration(
this.getClass().getClassLoader().getResourceAsStream("logging.properties"));
}
catch (final Exception e)
{
e.printStackTrace();
}
You can test your logger as follows:
this.log.log(Level.INFO, "This message goes to standard error and to the logfile");
this.log.log(Level.FINE, "This message only goes to the logfile");
For other logging facilities such as Log4j, there exist mechanisms which allow for auto-discovering the logging properties.
I have uploaded an example application as Maven project on GitHub.
Log4j
Log4j will use a configuration properties file if it is called log4j.properties and can be found on the classpath. What follows is a simple template configuration that makes Log4j log to console:
log4j.rootLogger=INFO, stderr
log4j.appender.stderr=org.apache.log4j.ConsoleAppender
log4j.appender.stderr.layout=org.apache.log4j.PatternLayout
log4j.appender.stderr.Target=System.err
# %m%n - print only the log message and a newline
# %d{ISO8601} %F:%L %n%6p %m%n - print date, file and line number in the first
# and priority plus message in a second line
log4j.appender.stderr.layout.ConversionPattern=%m%n
# Makes log4j print self-configuration messages
# log4j.debug=true
The patterns used by Log4j have a different notations than the format property. The output format of each line is determined by the PatternLayout.
Links
- [1] Sample Project hosted on GitHub