Nearby lessons
35 of 35Spring - Log4j Integration
- Understand Spring - Log4j Integration
- See working code examples
- Learn from common mistakes and Q&A
Learn Spring - Log4j Integration step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.
Log4j
Log4J is a reliable, fast and flexible framework written in JAVA to perform logging in Java applications and it is provided by Apache Software Foundations.
Log4j Features
Log4j is able to allow more than one thread at a time with out providing data inconsistency ,so that, Log4j is thread-safe. Log4j will not slow down the application execution, it will be optimized to improve application performance. Log4j is providing environment to send logging messages to more than one output appenders . Log4j supports internationalization. Log4j is providing services for both predefined and user defined facilities, it able to provide some customizations also. Log4j allows to set logging behaviours at runtime through the configuration file. Log4j is providing very good environment to traace Exceptions from its root. Log4j uses multiple levels like ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL to generate messages. Log4j allows to change the format of log output by extending Layout class. Log4j is using appenders to generate log messages.
Log4j Arch contains mainly the following Objects
- Logger
- Appender
- Layout
- Level
- LogManager
- Filter
- ObjectRender
Logger
This Object is responsibile to get logging messages from Java applications
Appender
The main intention of Appender object is to get logging messages from Logger object and publishing that logging messages to the preffered destinations. Each and Every Appender Object must have atleast one Destination object inorder to send logging messages.
EX: ConsoleAppender is able to store logging messages on Console.
Layout
The main intention of Layout object is to format logging messages in different styles.Layout Object is used by Appender object just before publishing Logging Messages.
Level
The main intention of Level object is to define granualarity and priority of any Logging information. Each and every Logging information must be with a particular Logging Level.
Log4j API has provided the following Levels to the Logging messages.
- ALL
- TRACE
- DEBUG
- ENFO
- WRAN
- ERROR
- FATAL
- OFF
Log4j is giving priorities for the logging messages in the following order. ALL >TRACE > DEBUGG > INFO > WARN > ERROR > FATAL>OFF
LogManager
LogManager is the central component , it able to manage Log4j framework, it will read all the initial configuration details from the configuration file and stored the Logger objects in namespace hierarchy with a particular reference name for futer reference. If our application access any Logger object on the basis of the reference name then LogManager will return the existed Logger object otherwise it will create new Logger object and return to the application.
Filter
The main intention of Filter object is used to analyze logging information and takes the decision whther the messages must be logged or not. An Appender object may have no of Filter objects, they must approve our logging message before publishing logging messages in destination.
ObjectRender
This Object will be used by Layout object in order to get string representation of the several objects which are passed through Log4j framework.
Log4j Internal Flow
- If we create Logger object in Java application then a request will be send to Log4j Software about to create Logger object.
- Log4j Software will search for log4j.properties/log4j.xml file in classpath, if it is existed then
Log4j Software will load and parse log4j configuration file then Log4j software will create Logger object.
- After creating Logger object, Log4j Software will return Logger object to Java Application.
- If we access any logger method from Logger reference then Java application will send logging responsibility to Log4j software.
- Log4j Software will activate Appender object inorder to perform logging.
- Appender will recognize all the filters which are associated then Appender will execute all the filters in sequence, where filters will filters the logging messages to persist or display.
- Appender will activate Layout object , it will apply the layout styles on the logging messages.
- After Styling Logging messages, Appender will activate Object Renderer to recognize the destination.
- Sending Logging messages to the respective Destination.
Log4j Configuration File
Log4j Configuration File includes all Log4j configuration details like rootLogger, Layout configurations, Appenders configuration,.
In Log4j , we are able to use the following two types of configuration files.
- log4j.properties
- log4j.xml
IN both the configuratin files, we have to use the following configurations at basic java applications.
- Declare rootLogger and initialize rootLogger
- Declare appender
- Declare Layout and its conversionPattern.
EX: log4j.properties
log4j.rootLogger =TRACE, CONSOLE log4j.appender.CONSOLE = org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.conversionPattern=%d{yyyy-mm-dd hh:mm:ss } : This is
%m%n
Where "log4j.rootLogger" property will take Logging LEVEL and appender name, where Log4j framework will display all the messages which are same as the specified Log
level and lower than the specified Log level. Where appender name is a name which is referring a particular Appender.
EX: log4j.rootLogger = TRACE, CONSOLE
Where "log4j.appender.CONSOLE" property will take a particular Appender like ConsoleAppender, FileAppender,...
EX: log4j.appender.CONSOLE = org.apache.log4j.ConsoleAppender
Where "log4j.appender.CONSOLE.layout" property will configure Layout configfuration.
EX: log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout
Where PattrenLayout needs a property like conversionPattern to take a particular pattern to display messages.
EX: "log4j.appender.CONSOLE.layout.conversionPattern = %m%n
Note: Where %m%n in the sense, %m is to display message and %n is to bring cursor to next line.
log4j.xml Configuration — log4j.xml
In XML confioguration we have to use the following configuration.
- Appender configuration.
- Layout Configuration
- Root Logger COnfiguration
To provide XML configuration then we have to use the following xml tags in log4j.xml file.
log4j.xml Configuration
Where <log4j:configuration> isa a root tag, it able to take log4j configuration details. Where <appender> tag is able to configure Appender class with a logical name. Where "name" attribute in <appender> tag will take logical name to the appender. Where "class" attribute in <appender> tag is able to take fully qualified name of the
Appender class, that is, "org.apache.log4j.ConsoleAppender" Where <layout> tag can be used to configure Layout class. Where "class" attribute in <layout> tag will take fully qualified name of Layout class, that is,
"org.apache.log4j.PatternLayout". Where <param> tag in <layout> tag will take layout parameter . Where "name" attribute will take parameter name, tyhat is , "ConversionPattern". Where "value" attribute will take value of the parameter , that is, %d{DD/MM/YYYY
HH:mm:SS} %-5p %c{1} - %m%n Where <root> tag will provide rootLogger configuration. Where <priority> tag tag will take logger level with "value" attribute. Where <appender-ref> tag will take logical name of the appender with "ref" attribute.
Steps to Use Log4j in Java Application
- Download log4j-1.2.17.zip from "https://logging.apache.org/log4j/1.2/download.html"
- Create Java project in Eclipse IDE and add log4j1.2.17.jar file in build path
- Create log4j configuration file[log4j.properties or log4j.xml].
- Create Java class.
- Run Java project [Suggestible in Debug mode].
Example:
log4j.properties — Log4jTest.java
log4j.rootLogger =FATAL, CONSOLE log4j.appender.CONSOLE = org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } : This is
%m%n
log4j.properties — log4j.xml
Note: If we want to use XML configuration then we have to use the following XML file
Appenders
Appender is an object, it can be used to get logging messages from Logger object and publishing that logging messages to the preffered destinations. Each and Every Appender Object must have atleast one Destination object inorder to send logging messages.
Log4j has provided the following appenders inorder to publish logging messages.
- ConsoleAppender
- FileAppender
- JDBCAppender
- JMSAppender
- SocketAppender
- SMTPAppender
- AsyncAppender
- AppenderSkeleton
- DailyRollingFileAppender
- ExternallyRolledFileAppender
- LF5Appender
- NTEventLogAppender
- NullAppender
- RollingFileAppender
- SocketHubAppender
- SyslogAppender
- TelnetAppender
- WriterAppender
If we want to manage all logging messages in a File then we have to use FileAppenders.
There are Four types of File Appenders.
- FileAppender
- RollingFileAppender
- DailyRollingFileAppender
- ExternallyRolledFileAppender
FileAppender
If we want to use FileAppender in Java applications then we have to use the following properties in log4j.properties file.
- log4j.rootLogger
- log4j.appender.Ref_Name
- log4j.appender.Ref_Name.File : It will name and location of the file to manage logging
messages.
- log4j.appender.Ref_Name.layout
- log4j.appender.Ref_Name.layout.ConversionProperty
EX:
log4j.properties — Log4jTest.java
log4j.rootLogger =ALL, FILE log4j.appender.FILE = org.apache.log4j.FileAppender log4j.appender.FILE.File=./logging/logs.log log4j.appender.FILE.layout = org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } : This is
%m%n
log4j.properties
If we want to use both ConsoleAppender and FileAppender in Java Applications then we have to define two Ref_Names at 'log4j.rootLogger' property.
EX:
log4j.properties
log4j.rootLogger =ALL, CONSOLE, FILE
#ConsoleAppender Configuration
log4j.appender.CONSOLE = org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p
: This is %m%n
#FileAppender Configuration
log4j.appender.FILE = org.apache.log4j.FileAppender log4j.appender.FILE.File=./logging/logs.log log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p — Log4jTest.java
This is %m%n
RollingFileAppender
The main intention of RollingFileAppender is to manage logging messages to the other new files when the present log file is getting exceded as per the file size limit.
If we want to use RollingFileAppender in log4j applications then we have to use "org.apache.log4j.RollingFileAppender" class and we have to use all the FileAppender properties and the following extra properties.
- log4j.appender.Ref_Name.MaxFileSize : It will take max File size in the form of KB
- log4j.appender.Ref_Name.MaxBackupIndex= It able to create maximum backup files.
EX:
log4j.properties
log4j.rootLogger =ALL, FILE
#FileAppender Configuration
log4j.appender.FILE = org.apache.log4j.RollingFileAppender log4j.appender.FILE.file= e:/loggers/logs.txt log4j.appender.FILE.MaxFileSize= 2kb log4j.appender.FILE.MaxBackupIndex= 3 log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p — Log4jTest.java
This is %m%n
DailyRollingFileAppender
The main intention of DailyRollingFileAppender is to roll files in FileAppender on daily basis.
If we want to use DailyRollingFileAppender in log4j applications then we have to use "org.apache.log4j.DailyRollingFileAppender" and we have to use "datePattern" property in properties file. Note: If we are using DailyRollingFileAppender in our application then it is not required to use "maxFileSize" and "maxBackupIndex" properties in log4j.properties file.
Note: The default pattern for datePattern property is '.' '.' yyyy-MM-dd , it will roll over every day midnight
For "datePattern" property we are able to use the following values.
- '.' yyyy-MM : It will roll over at the end of each month and at the beginning of the next month.
- '.' yyyy-MM-dd : It will roll over at midnight each day.
- '.' yyyy-MM-dd-a :It will roll over at midday and midnight of each day.
- '.' yyyy-MM-dd-HH : It will roll over at the top of every hour.
- '.' yyyy-MM-dd-HH-mm : It will roll over every minute.
- '.' yyyy-ww : It will roll over on the first day of each week depending upon the locale.
Example:
log4j.properties
log4j.rootLogger =ALL, FILE
#FileAppender Configuration
log4j.appender.FILE = org.apache.log4j.DailyRollingFileAppender log4j.appender.FILE.file= e:/loggers/logs.txt log4j.appender.FILE.DatePattern='.' yyyy-MM-dd-HH-mm #log4j.appender.FILE.MaxFileSize= 2kb #log4j.appender.FILE.MaxBackupIndex= 3 log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p — Log4jTest.java
This is %m%n
ExternallyRolledFileAppender
This appender listens on a socket on the port specified by the Port property for a "RollOver" message. When such a message is received, the underlying log file is rolled over and an acknowledgment message is sent back to the process initiating the roll over.
Note: ExternallyRolledFileAppender is required Socket Programming and it is deprecated Layouts
Layouts
The main intention of Layout is to define a partidular Structer for the logging messages.
There are four types of Layouts existed in Log4j.
- SimpleLayout
- PatternLayout
- HTMLLayout
- XMLLayout
Simple Layout
SimpleLayout is able to prepare logging messages with "LEVEL - Log_Message" . Log4j has provided a predefiend class to represent Simple Layout,that is, org.apache.log4j.SimpleLayout
EX:
log4j.properties — Test.java
log4j.rootLogger = ALL, FILE log4j.appender.FILE = org.apache.log4j.FileAppender log4j.appender.FILE.file = E:/loggers/logs.log log4j.appender.FILE.layout = org.apache.log4j.SimpleLayout
OP
TRACE - Trace Message DEBUG - Debug Message INFO - Info Message WARN - Warn Message ERROR - Error Message FATAL - Fatal Message
Pattern Layout
It able to prepare logging messages w.r.t the provided pattern. To represent Pattern Layout, Log4j has provided a predefined class in the form of "org.apache.log4j.PatternLayout".
To define pattern for the logging messages, we must use "ConversionPattern" property from PatternLayout class.
EX:
log4j.properties
log4j.rootLogger = ALL, FILE log4j.appender.FILE = org.apache.log4j.FileAppender log4j.appender.FILE.file = E:/loggers/logs.log log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern = %d{dd/MM/YYYY HH:mm:SS} %-c %p — Log4jTest.java
This Is %m%n
OP
22/08/2018 18:50:885 com.durgasoft.log4j.Log4jTest TRACE : This Is Trace Message 22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest DEBUG : This Is Debug Message 22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest INFO : This Is Info Message 22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest WARN : This Is Warn Message 22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest ERROR : This Is Error Message 22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest FATAL : This Is Fatal Message
Note: We will use these patterns in general in PatternLayout for ConversionPattern property.
%d ----> Date %c ----> Class to which we are providing Logging %P ----> Logging Level %L ----> Line NUmber %m ----> Logging Message %n ----> New Line Character
HTML Layout
It able to provide all logging messages in the form of Html file. To represent this Layout Log4j has provided a predefined class in the form of "org.apache.log4j.HTMLLayout"
EX:
log4j.properties — Log4jTest.java
log4j.rootLogger = ALL, FILE log4j.appender.FILE = org.apache.log4j.FileAppender log4j.appender.FILE.file = E:/loggers/logs.html log4j.appender.FILE.layout = org.apache.log4j.HTMLLayout
XML Layout
It able to provide logging messages in the form of XML document. To rperepsent XMLLayout, Log4j has provided a predefined class in the form of "org.apache.log4j.xml.XMLLayout"
EX:
log4j.properties — Log4jTest.java
log4j.rootLogger = ALL, FILE log4j.appender.FILE = org.apache.log4j.FileAppender log4j.appender.FILE.file = E:/loggers/logs.xml log4j.appender.FILE.layout = org.apache.log4j.xml.XMLLayout
log4j.properties — Test.java
log4j.rootLogger = ALL, FILE log4j.appender.FILE = org.apache.log4j.FileAppender log4j.appender.FILE.file = E:/loggers/logs.txt log4j.appender.FILE.append = false log4j.appender.FILE.layout = org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern = %d{dd/MM/YYYY HH:mm:SS} %-c %p
%L : %m%n
Log4j in Web Applications — loginform.html
- Keep Log4j1.2.7.jar in web application lib folder.
- Prepare Configuration File under src folder / under classes folder.
- It is suggestible to use FileAppenders.
- In Servlets generate Loggers.
Example:
Log4j in Web Applications — success.html
Log4j in Web Applications — failure.html
Log4j in Web Applications — web.xml
log4j.properties — LoginServlet.java
log4j.rootLogger = ALL, FILE log4j.appender.FILE = org.apache.log4j.FileAppender log4j.appender.FILE.file = E:/loggers/logs.txt #log4j.appender.FILE.datePattern = '.'dd-MM-yyyy-HH-mm log4j.appender.FILE.layout = org.apache.log4j.PatternLayout #log4j.appender.FILE.layout = org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern = %d{dd/MM/YYYY HH:mm:SS} %-C %p
%L : %m%n
log4j.properties — UserService.java
- Key ideas of Spring - Log4j Integration explained simply
- Ready-to-use code examples
- Exam-style questions at the end