QA's approach 2 Java - Logging API - Log4j
Log4j
Log4j is a Framework(API) written in Java & distributed under Apache Software license, used for debugging.Log4j has 3 main components:
1. loggers: To capture the logging information
2. appenders: To publish the logging information to various destinations. An output destination is called an appender.
3. layouts: To format logging information in different styles.
There are three ways to configure log4j:
1. Using properties file.
2. Using Java code programatically.
3. Using XML file.
Configuring Log4j using properties files & programmatically
Configuring log4j involves the following tasks:
1. Configuring the root logger
2. Configuring individual logger
3. Specifying appenders
4. Specifying message layout
Configure the root logger
The root logger is the base logger from which other loggers inherits.
Syntax for configuring the root logger is as follows:
log4j.rootLogger=level[, appender1, appender2…]
Where level can be one of the following values (in ascending order of severity): ALL, DEBUG, INFO, WARN, ERROR, FATAL, and OFF.
These constants are defined in the class org.apache.log4j.Level. appender1, appender2 are names of the appenders that configures how messages are logged, i.e. to standard console or log files.
One logger can have multiple appenders, each one is configured individually by some properties start with log4j.appender.<appender_name>.For example:
log4j.rootLogger=DEBUG, ConsoleAppender, FileAppender
That tell log4j configures the root logger to log all messages from DEBUG level to console and to log file.
Programmatically, the root logger can be obtained by invoking the static method
Logger.getRootLogger() which returns a Logger object.
The level can be set via setLevel(Level) method;
Appender can be specified via addAppender(Appender) method of the Logger object, respectively.
Configure an individual logger
It is possible to configure loggers other than the root logger. The syntax is similar:
log4j.logger.<logger-name>=level[, appender1, appender2…]
where <logger-name> is name of a particular logger in the source code, for example: if you define a logger called com.mycompany.DatabaseUtil, then you can configure it through log4j’s configuration file as follows:
log4j.logger.com.mycompany.DatabaseUtil=INFO, ConsoleAppender
Programmatically, an individual logger can be created or retrieved (if already exists) by invoking the static methods Logger.getLogger(Class) or Logger.getLogger(String). For example:
Logger logger1 = Logger.getLogger(“com.Test.ClassName”);
Logger logger2 = Logger.getLogger(ClassName.class);
Specify appenders
In log4j’s terms, an appender specifies how messages are logged. An appender is a class that implements the interface org.apache.log4j.Appender and is configured in configuration file follows this syntax:
log4j.appender.<appender_name>=<appender_class_name>
log4j.appender.<appender_name>.<property1_name>=<property1_value>
log4j.appender.<appender_name>.<property2_name>=<property2_value>
Where appender_name must match the name specified in the configuration of root logger or a particular logger.
appender_class_name: fully qualified name of a class that implements org.apache.log4j.Appender interface, for example org.apache.log4j.ConsoleAppender for console appender, org.apache.log4j.FileAppender for file appender, to name a few.
property1_name: name of a particular property of the appender, depending on type of appender.
property1_value: value of the corresponding property.
To see a complete list of appender classes provided by log4j, go to: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Appender.html, under “All known implementing classes”.
The following example indicates the configuration for a console appender of the root logger:
log4j.rootLogger=DEBUG, Console
log4j.appender.Console =org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
Programmatically, an appender can be created and assigned to a logger as follows:
Appender console = new ConsoleAppender();
Logger root = Logger.getRootLogger();
root.addAppender(console);
Specify message layout
With log4j, messages are logged in a specified format which is referred as “layout”. Each appender is associated with a layout follows this syntax:
log4j.appender.<appender_name>.layout=<layout_class_name>
log4j.appender.<appender_name>.layout.ConversionPattern=<conversion_pattern>
layout_class_name: fully qualified name of a class that extends the abstract class org.apache.log4j.Layout,
for example org.apache.log4j.PatternLayout which formats the log message by a configurable pattern.
To see a complete list of layout classes provided by log4j, go to http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Layout.html, under “Direct Known Subclasses”.
conversion_pattern: specifies the pattern which formats log messages for the layout org.apache.log4j.PatternLayout,
for example:
log4j.appender.console.layout.ConversionPattern=[%t] %-5p %c - %m%n
Each conversion specifier must follow this format:
<percent sign (%)>[format modifiers]<conversion characters>
Where, the percent sign (%) is required which indicates the start of a specifier.
Format modifiers are optional. They specify field width, padding, left and right justification.
Conversion character is required. It specifies what type of information to be logged, i.e. date, time, category, priority, thread name, etc.
To see a complete list of conversion characters, go to: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html
The specifiers used in the above example:
t: name of the current executing thread.
p: priority
c: category
m: log message.
n: line separator character.
Example Configuration File:
log4j.properties
========================================================================
# Root logger option
log4j.rootLogger=DEBUG, stdout, file
# Redirect log messages to console
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{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
========================================================================
To understand the symbols in Conversion Pattern, follow the below
%d{yyyy-MM-dd HH:mm:ss} = Date and time format, refer to SimpleDateFormat JavaDoc.
%-5p = The logging priority, like DEBUG or ERROR. The -5 is optional, for the pretty print format.
%c{1} = The logging name we set via getLogger()
%L = The line number from where the logging request.
%m%n = The message to log and line break.
It is also possible to write log4j’s logging statements without making any configuration, which is explained as below
==========================================
Logger logger = Logger.getLogger(ClassName.class);
BasicConfigurator.configure();
logger.info("This is a test log statement");
==========================================
above code will print out logging statements to the standard console.
Example Program for Logging test:
import java.io.File;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Test {
static Logger logger = Logger.getLogger(Test.class);
public static void main(String[] args) {
String log4jConfigFile = "C:\\Users\\user\\workspace\\Newfolder\\javaForQA\\Log4j.properties";
PropertyConfigurator.configure(log4jConfigFile);
logger.debug("this is a debug log message");
logger.info("this is a information log message");
logger.warn("this is a warning log message");
}
}
Configuring Log4j using Log4j.xml
======================================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'>
<root>
<level value="ERROR" />
<appender-ref ref="file" />
</root>
<appender name="file" class="org.apache.log4j.RollingFileAppender">
<param name="append" value="false" />
<param name="maxFileSize" value="10KB" />
<param name="maxBackupIndex" value="5" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
</log4j:configuration>
======================================================================
Comments
Post a Comment