Log4j :
Log4j is a Reliable, Fast and Flexible Logging Framework (APIs) written in Java which is distributed under the Apache Software License.
Log4j has three main components:
- loggers: Responsible for capturing logging information.
- appenders : Responsible for publishing logging information to various preferred destinations.
- layouts: Responsible to format logging information in different styles.
log4j Features:- log4j is thread-safe.
- log4j is optimized for speed.
- log4j is based on a named logger hierarchy.
- log4j supports multiple output appenders per logger.
- log4j supports internationalization.
- log4j is not restricted to a predefined set of facilities.
- Logging behavior can be set at runtime using a configuration file.
- log4j is designed to handle Java Exceptions from the start.
- log4j uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
- The format of the log output can be easily changed by extending the Layout class.
- The target of the log output as well as the writing strategy can be altered by implementations of the Appender interface.
- log4j is fail-stop. However, altough it certainly strives to ensure delivery, log4j does not guarantee that each log statement will be delivered to its destination.log4j Installation :Log4j API package is distributed under the Apache Software LicensePut log4j-1.2.15.jar in your project classpath(web application : classes folder (all files in classed folder are in classpath))
There are two type of objects available with Log4j framework.
- Core Objects: These are mandatory objects of the framework and required to use the framework.Logger ObjectLayout ObjectAppender Object
- Support Objects: These are optional objects of the framework and support core objects to perform addition but important tasks.Level ObjectFilter ObjectObject RendererLogManager
Configuring log4j involves assigning the Level, defining Appender, and specifying Layout objects in a configuration file.LogManager looks for a file named log4j.properties in the CLASSPATH.- The level of the root logger is defined as DEBUG and attaches appender named X to it.
- Set the appender named X to be a valid appender.
- Set the layout for the appender X
# Define the root logger with appender file log4j.rootLogger = DEBUG, FILE # Define the file appender log4j.appender.FILE=org.apache.log4j.FileAppender log4j.appender.FILE.File=${log}/log.out # Define the layout for file appender log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n
It is important to note that log4j supports UNIX-style variable substitution such as ${variableName}.Debug Level:
We have used DEBUG with both the appenders. All the possible options are:- TRACE
- DEBUG
- INFO
- WARN
- ERROR
- FATAL
- ALL
These levels would be explained in Log4j Logging Levels.Property Description layout Appender uses the Layout objects and the conversion pattern associated with them to format the logging information. target The target may be a console, a file, or another item depending on the appender. level The level is required to control the filteration of the log messages. threshold Appender can have a threshold level associated with it independent of the logger level. The Appender ignores any logging messages that have a level lower than the threshold level. filter The Filter objects can analyze logging information beyond level matching and decide whether logging requests should be handled by a particular Appender or ignored. We can add an Appender object to a Logger by including the following setting in the configuration file with the following method:log4j.logger.[logger-name]=level, appender1,appender..n
We have used only one appender FileAppender in our example above. All the possible appender options are:- AppenderSkeleton
- AsyncAppender
- ConsoleAppender
- DailyRollingFileAppender
- ExternallyRolledFileAppender
- FileAppender
- JDBCAppender
- JMSAppender
- LF5Appender
- NTEventLogAppender
- NullAppender
- RollingFileAppender
- SMTPAppender
- SocketAppender
- SocketHubAppender
- SyslogAppender
- TelnetAppender
- WriterAppender
static Logger log = Logger.getLogger(log4jExample.class.getName());
XML Configuration :
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"><!-- general application log --> <appender name="BarLogFile" class="org.apache.log4j.FileAppender"> <param name="File" value="bar.log" /> <param name="Threshold" value="INFO" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/> </layout> </appender> <!-- additional fooSystem logging --> <appender name="BlatzLogFile" class="org.apache.log4j.FileAppender"> <param name="File" value="blatz.log" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/> </layout> </appender> <!-- important to note logger of com.foo.bar package will be appended in BarLogFile--> <logger name="com.foo.bar"> <appender-ref ref="BarLogFile"/> </logger>
<logger name="com.bar.blatz"> <appender-ref ref="BlatzLogFile"/> </logger> <root> <level value="INFO"/> <!-- no appender, output will be swallowed (I think) --> </root><!-- important to note logger of com.foo.bar package will be appended in BlatzLogFile--></log4j:configuration>
If you add an appender-ref to the root element, it will also receive com.foo.bar etc messages. You can stop that by specifying 'additivity="false"' on the loggers.
Logging in Multiple Files:
There may be a requirement when you want to write your log message into multiple files for certain reasons like for example if file size reaches to a certain threshold etc.To write your logging information into multiple files you would have to useorg.apache.log4j.RollingFileAppender class which extends the FileAppender class and inherits all its properties.There are following configurable parameters in addition to what have been mentioned above for FileAppender:Property Description maxFileSize This is the critical size of the file above which the file will be rolled. Default value is 10MB maxBackupIndex This property denotes the number of backup files to be created. Default value is 1.
Daily Log File Generation:
There may be a requirement when you want to generate your log files on per day basis to keep a clean record of your logging information.To write your logging information into files on daily basis you would have to useorg.apache.log4j.DailyRollingFileAppender class which extends the FileAppender class and inherits all its properties.The log4j API provides the org.apache.log4j.jdbc.JDBCAppender object, which is capable of putting logging information in a specified database.JDBCAppender Configuration:
Property Description bufferSize Sets the buffer size. Default size is 1. driver Sets the driver class to the specified string. If no driver class is specified, defaults to sun.jdbc.odbc.JdbcOdbcDriver. layout Sets the layout to be used. Default layout is org.apache.log4j.PatternLayout. password Sets the database password. sql Specifies SQL statement to be executed every time a logging event occurs. This could be INSERT, UPDATE, or DELETE. URL Sets the JDBC URL user Sets the database user name Log Table Configuration:
Before you start using JDBC based logging, you shold create a table where all the log information would be maintained. Following is the SQL Statement for Creating the LOGS Table:CREATE TABLE LOGS (USER_ID VARCHAR(20) NOT NULL, DATED DATE NOT NULL, LOGGER VARCHAR(50) NOT NULL, LEVEL VARCHAR(10) NOT NULL, MESSAGE VARCHAR(1000) NOT NULL );

No comments:
Post a Comment