Log4j is a framework which helps the java user to record the messages (logs) during the execution time. Logs are nothing but the detailed execution steps.
Log4j write all the messages into files, files could be in many formats like a text file, log file, html file. Users have to configure the log4j before using it.
We can configure the log4j in two ways :
Components of log4j :
Sample code for Logging in log4j
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class FirstLog {
static Logger log = Logger.getLogger(FirstLog.class);
public static void main(String[] args) {
//PropertiesConfigurator is used to configure logger from a properties file
PropertyConfigurator.configure("C:\~\log4j.properties");
//log the message to file
log.trace("This is a debug message");
log.info("This is an info message");
}
}
Logger captures the log messages generated by the framework, and it passes the logs to appends. Logger decides where to send the information like whether to file or to console. Loggers also decide what priority level to be captured.
Logger Priority Levels : All the levels are static variable and every level indicates a specific int value, as int value increases the rank also increases i.e max int values have max rank, least int value has the least rank.
ALL -Integer.MIN_VAL : The ALL has the lowest possible rank and lowest int values, it is intended to turn on all logging.
TRACE - 5000 : This log4j level gives more detailed information than the DEBUG level and sits top of the hierarchy after ALL.
DEBUG - 10000 : To debug the application, developers give the priority to debug. Level of message logged will be focused on providing support to an application developer
INFO - 20000 : Provides informational messages that highlight the progress of the application execution.
WARN - 30000 : The messages coming out of this level may not halt the progress of the system, but informs the user something unexpected is happening
ERROR - 40000 : The ERROR level designates error events that might still allow the application to continue running, means a particular part is failing but not a showstopper.
FATAL - 50000 : The FATAL level designates very severe error events that will presumably lead the application to abort, means it is a showstopper.
OFF - Integer.MAX_VAL : Does not capture any log and it's int value is Maximum value an integer can hold.
Appenders writes the log messages decided by the logger into a file or to a database. Appenders delegates the message to the formatter. There are different kind of appenders
The Layout component defines the format in which the log statements are written to the log destination by appender, like html or .log so on. There are different kind of layout are present
We can associate log4j with our framework in a few steps.
1. Goto apache log4j site : https://logging.apache.org/log4j/1.2/
2. Click download Link
3. Click log4j.version.zip file from the table for windows
4. Click on the recommended mirror site link ( it may change based on your location )
5. Extact the downloaded zip file, and you can find the log4j.version.jar file
6. Open Eclipse and go to build path of the project
7. Add the log4j jar using Add External jar option
8. Inside java class try to type Logger, you should get a suggestion from the Log4j. If you are seeing below suggestion your installation is successful.
We can configure the log4j using a properties file, the properties file is nothing but hold the key-value pair.
Properties File:
Explanation of Properties File : 1. Logger section defines what is the level of Priority and where it send the logs. Here the Priority is 'DEBUG' and the destination is 'file'
# Root logger denotes where to write and a priority level to write
log4j.rootLogger=DEBUG, file
2. Appender Section defines the details of the destination, which nothing but what is the type of appends, file location and the file size. Here Appender Type is RollingFileAppender, File Location is C:~\firstLogOutput.log, file Size :10mb.
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\~\firstLogOutput.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
3. Layout defines how the out put should look like. Here layout type is PatternLayout. Refer for Pattern Layout
# layout of the log output pattern
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
Integration of Properties file with Log4J
After defining the values in properties file we have to integrate the properties file to the log4j system. Please find the steps to integrate
1. Create java class inside java Project.
2. Create the logger object by calling the getLogger method from the Logger Class, pass the Log name as a parameter, most of the tie people pass the class name as a parameter.
static Logger log = Logger.getLogger(FirstLog.class);
3. Load the peroperties file using configure methid from PropertyConfigurator class, pass the properties file path as the parameter.
//PropertiesConfigurator is used to configure logger from the properties file
PropertyConfigurator.configure("C:\~\log4j.properties");
4. Call the methosd from the Logger class object (log)
//log the message to file
log.trace("This is a debug message");
log.info("This is an info message");
5. Execute the file like normal java class and find the output file.
Complete program for Log4j with properties file
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class FirstLog {
static Logger log = Logger.getLogger(FirstLog.class);
public static void main(String[] args) {
//PropertiesConfigurator is used to configure logger from the properties file
PropertyConfigurator.configure("C:\~\log4j.properties");
//log the message to file
log.trace("This is a debug message");
log.info("This is an info message");
}
}
We can also configure the log4j logging system with xml configuration file. Please follow below steps to configure the log4j with xml.
1. All the attributes between &lappender> are appender component properties.
2. name: fileAppender and the value is Rolling file appender , which means use RollingFileAppender as output type.
<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
3. name:File and value location of the file point to where to store the output.
<param name="File" value="C:\~\firstXMLLog.log"/>
4. layout tag mention what kind of the layout we want in output (here patteren layout)
<layout class="org.apache.log4j.PatternLayout">
5. priority tag defines what is the priority level
<priority value ="debug">
Integrate XML with Log4j
1. Create Java class under java project 2. Create object for logger class using getLogger() method from Logger class.
static Logger log = Logger.getLogger(LOgWithXML.class);
3. Load the xml file using confugure method from the DOMConfigurator class
//DOMConfigurator is used to configure logger from xml configuration file
DOMConfigurator.configure("C:\~\log4j.xml");
4. Log an message to the file
//Log to file
log.fatal("Log4j XML configuration is successful !!");
Complete program for XML integration with log4j
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
public class LOgWithXML
{
static Logger log = Logger.getLogger(LOgWithXML.class);
public static void main(String[] args)
{
//DOMConfigurator is used to configure logger from xml configuration file
DOMConfigurator.configure("C:\~\log4j.xml");
//Log to file
log.fatal("Log4j XML configuration is successful !!");
}
}
his layout outputs events in a HTML table. Appenders using this layout should have their encoding set to UTF-8 or UTF-16, otherwise events containing non ASCII characters could result in corrupted log files.
log4j-html.properties :
# Define the root logger with file appender
log4j.rootLogger = DEBUG, HTML
# Define the file appender
log4j.appender.HTML=org.apache.log4j.FileAppender
log4j.appender.HTML.File=C:\~\HTMLlog.html
# Define the html layout for file appender
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=HTML log
log4j.appender.HTML.layout.LocationInfo=true
log4j.appender.HTML.Threshold=DEBUG
HTMLLog.java :
package loggy;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class HTMLLog {
static Logger log = Logger.getLogger(FirstLog.class);
public static void main(String[] args) {
//PropertiesConfigurator is used to configure logger from properties file
PropertyConfigurator.configure("C:\~\log4j-html.properties");
//log the message to file
log.trace("This is a trace message");
log.info("This is an info message");
log.warn("This is an warn message");
log.error("This is an error message");
log.fatal("This is an fatal message");
}
}
Output :
I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.