Tuesday, September 7, 2010

What is Log4j

What is Log4j

Log4j is a tool to help the programmer output log statements to a variety of output targets.
With log4j it is possible to enable logging at runtime without modifying the application binary.

What are the components of Log4j

Log4j has three main components: loggers, appenders and layouts.

ü        There are six different level of logging supported by logger component (TRACE, DEBUG, INFO, WARN, ERROR, FATAL)
ü        Appender specifies the destination where the logging information should go for example Console, File, Email, Database etc.
ü        The layout is responsible for formatting the logging request according to the user's wishes

How to use Log4j

1.        Create a java project
2.        Add latest log4j jar file to the class path (log4j-1.2.14.jar)
3.        Create log4.properties in your 'src' folder. When the application is executed log4j.properties is automatically detected in 'src' folder.

### direct log messages to stdout ###

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.out

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=all, stdout



4.        Create a java class LogManager.java as shown below
package training;

import org.apache.log4j.Logger;

public class LoggingManager {

        private static Logger log = Logger.getLogger(LoggingManager.class);

        public static void main(String args[]){

                log.trace("Trace");

                log.debug("Debug");

                log.info("Info");

                log.warn("Warn");

                log.error("Error");

                log.fatal("Fatal");

        }

}



5.        Execute the LoggingManager class you should see output like below
11:46:57,409 TRACE LoggingManager:9 - Trace

11:46:57,409 DEBUG LoggingManager:10 - Debug

11:46:57,409  INFO LoggingManager:11 - Info

11:46:57,409  WARN LoggingManager:12 - Warn

11:46:57,409 ERROR LoggingManager:13 - Error

11:46:57,409 FATAL LoggingManager:14 - Fatal


How to configure Log4j

Let's look at the configuration in log4j.properties file

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.out


The above lines specify that all the logging messages should be handled by ConsoleAppender i.e. they will be printed on the console. An appender specifies where your log messages are written to. There is a wide choice of appenders available and custom appenders can be created as well.

Console Appender Logs to a console
File Appender Logs to file
SMTP Appender Logs by email
RollingFileAppender Logs to a file, starts a new file once the max size is reached. (An alternative is the DailyRollingFileAppender  which creates on file per day)


We can find all options on the following API page:
http://logging.apache.org/log4j/docs/api/org/apache/log4j/AppenderSkeleton.html


The layout specifies how a log message looks like, the below line defines which layout to be used.
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout


The best up-to-date documentation about available layouts can be found in the API documentation:
http://logging.apache.org/log4j/docs/api/org/apache/log4j/Layout.html

Another parameter of pattern layout defines how the information to be logged.
log4j.appender.stdout.layout.ConversionPattern  =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n

%d {ABSOLUTE}   Used to output the date of the logging event.  ABSOLUTE specifies the date formatter
%p Used to output priority of the logging event. %5p means the priority of the logging event should be left justified to a width of five characters
%c Used to output the category of the logging event.
%L Used to output the line number from where the logging request was issued.
%m Used to output the application supplied message associated with the logging event.
%n Outputs the platform dependent line separator character or characters


The options to influence the layout are explained in the API documentation:
http://logging.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html

The below line configures the log level for logger,
log4j.rootLogger = all, stdout


For programmatically setting the log level use below line
Logger.getRootLogger().setLevel(Level.WARN)
all All levels including custom levels
trace development only, can be used to follow the program execution.
debug developing only, for debugging purpose
info Production optionally, Course grained (rarely written information), I use it to print that a configuration is initialized, a long running import job is starting and ending.
warn Production, simple application error or unexpected behavior. Application can continue. I warn for example in case of bad login attempt, unexpected data during import jobs
error Production, application error/exception but application can continue. Part of the application is probably not working.
fatal Production, fatal application error/exception, application cannot continue, for example database is down.




No comments:

Post a Comment