Logging is done with log4j. The class that wishes to use lgo4j logger has to declare it as a static instance variable:
static org.apache.log4j.Logger log =
org.apache.log4j.Logger.getLogger(SessionListener.class);
In the above example the class
SessionListener defines static
log variable. From any method of this class we can make a call to logging methods on this object. There are 3 basic methods:
- log.debug("some string");
- log.info("some string");
- log.warn("some string");
Depending on level of logging configured for this class the message will be either printed out or suppressed.
Here is the example _
log4j.properties file:
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=INFO, CONSOLE, R
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppenderlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%5p [%t] - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=application.loglog4j.appender.R.MaxFileSize=5MB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=5log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%5p - %d [%t] (%F:%L) %c - %m%n
#log4j.logger.com=DEBUG;
log4j.logger.com.custommode.=DEBUG;
It defines two appenders
CONSOLE and
R (which is a file appender writing to application.log file). The default logging level is set to be INFO (so the debug messages will not output). We can turn different level of messages on package level. For instance in the above example package
com.custommode has DEBUG level enabled.
To improove the performance it's recommended to wrap blocks of debug statements with if/else logic like this:
if(log.isDebugEnabled()) {
log.debug("message1" + "message2" + object3);
}
If not wrapped with the if/else logic the code above would execute string concatination which is very expensive in java every time, even if DEBUG is disabled.