Log 4j Tutorial
Log 4j Tutorial
Tutorial
Apache Log4j Logging Framework
Tutorial with Example Projects
JournalDev.com
Table of Contents
1.
Log4j Tutorial
2.
Log4j Levels
3.
Log4j Appenders
4.
Log4j Tutorial
Pankaj Kumar
Log4j Jars
There are many ways to get log4j jars.
1. My favourite is to get all the dependencies through Maven. You can add
below dependencies in your pom.xml file to get log4j jar. <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2. If you are using gradle, then add dependency as:
'log4j:log4j:1.2.17'
3. If you are not using any build tools, you can download the log4j jar from
Apache Log4j Official page and include into your project classpath.
Log4j Configuration
Log4j supports both properties based as well as XML based configuration.
Here I will use XML based configuration, you can see log4j properties based
configuration in the linked post.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
debug="false">
<!-- console appender -->
logging level, class name with line number. We can define any number of
appenders in our log4j configuration file.
logger: It's used to provide mapping between java packages/classes with
appenders and logging levels. As you can see, multiple appenders can be
used with a single logger. If multiple logger matches with the java class
package, more specific one is used.
root: This is used when there is no logger defined for java packages. For
example, if have some classes in com.journaldev.beans package
then it won't match with any logger. So root logger will be used for
logging configurations.
Once log4j configuration file is ready, we have to configure it in the code
before we can actually start logging. Below is the way to do that.
//for XML based configuration
DOMConfigurator.configure("log4j.xml");
//for properties based configuration
PropertyConfigurator.configure("log4j.properties");
Note that if our log4j configuration file name is log4j.xml or
log4j.properties , then we can skip this step because log4j tries to
automatically load these files from classpath.
Log4j usage
Now let's see how they can be used in the code. We have created two
classes for our above defined loggers.
package com.journaldev.log4j.main;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import com.journaldev.log4j.logic.MathUtils;
debug="false">
<!-- console appender -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c1 - %m%n" />
</layout>
</appender>
<!-- rolling file appender -->
<appender name="file" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="$catalina.home/logs/main.log" />
<param name="Append" value="true" />
<param name="ImmediateFlush" value="true" />
<param name="MaxFileSize" value="10MB" />
<param name="MaxBackupIndex" value="5" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %dZ %-5p (%F:%L) %m%n" />
</layout>
</appender>
<logger name="com.journaldev.log4j" additivity="false">
<level value="DEBUG" />
<appender-ref ref="file" />
<appender-ref ref="console" />
</logger>
<root>
<priority value="DEBUG" />
<appender-ref ref="file" />
<appender-ref ref="console" />
</root>
</log4j:configuration>
More of less it's similar to earlier configuration, except that we are injecting
catalina.home variable to generate log files into tomcat logs directory.
Since we have to configure log4j before it's being used, we can load it by
defining a ServletContextListener as below.
package com.journaldev.log4j.servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.apache.log4j.xml.DOMConfigurator;
@WebListener
public final class Log4jInitListener implements ServletContextListener
public Log4jInitListener()
public void contextDestroyed(ServletContextEvent
paramServletContextEvent)
out.append("\n\nHello "+name);
out.flush();
Just export the project as WAR file and then deploy into Tomcat server,
below image shows when we call the servlet in browser.
You will get below kind of logs in tomcat logs directory main.log file.
pankaj:logs pankaj$ tail -f main.log
2016-05-12 21:46:33,038 +0530 INFO (MyServlet.java:29) - Name parameter
value = Pankaj
Since we are also logging to console that goes to catalina.out file, you will
find below logs in catalina log file.
pankaj:logs pankaj$ tail -f catalina.out
INFO MyServlet - Name parameter value = Pankaj
That's it for a quick tutorial on log4j.
References:
Log4j Official Website
Log4j on Wikipedia
Log4j initialization by implementing LifecycleListener
Log4j Levels
Pankaj Kumar
You will notice that there are many methods to log messages in log4j. For
example:
logger.trace("My Log message");
logger.debug("My Log message");
logger.info("My Log message");
Actually they corresponds to log4j levels.
Log4j Levels
Log4j provides many logging levels. Below is the complete list.
1. TRACE: The TRACE Level designates finer-grained informational events
than the DEBUG.
2. DEBUG: The DEBUG Level designates fine-grained informational events
that are most useful to debug an application.
3. INFO: The INFO level designates informational messages that highlight
the progress of the application at coarse-grained level.
4. WARN: The WARN level designates potentially harmful situations.
5. ERROR: The ERROR level designates error events that might still allow
the application to continue running.
6. FATAL: The FATAL level designates very severe error events that will
presumably lead the application to abort.
7. ALL: The ALL has the lowest possible rank and is intended to turn on all
logging.
8. OFF: The OFF has the highest possible rank and is intended to turn off
logging.
ALL and OFF are special logging levels and should be used in extreme
situations. I have never used these personally at any point of time.
Log4j Filters
Let's say we want to log only INFO and FATAL events but not WARN and
ERROR events. In these scenarios, we can take help of log4j Filters. We can
extend org.apache.log4j.spi.Filter class and implements it's
decide(LoggingEvent event) method to provide custom filtering
capabilities.
package com.journaldev.log4j.filters;
import org.apache.log4j.Level;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;
public class MyLog4jFilter extends Filter
/**
* My custom filter to only log INFO and FATAL events
*/
@Override
public int decide(LoggingEvent event)
if(event.getLevel() == Level.INFO || event.getLevel() == Level.FATAL)
return ACCEPT;
else return DENY;
Above custom Filter will log only INFO and FATAL events, below is the XML
log4j configuration for this.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
debug="false">
<!-- console appender -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c1 - %m%n" />
</layout>
<filter class="com.journaldev.log4j.filters.MyLog4jFilter" />
</appender>
<logger name="com.journaldev.log4j" additivity="false">
<level value="TRACE" />
<appender-ref ref="console" />
</logger>
<root>
<priority value="DEBUG" />
<appender-ref ref="console" />
</root>
</log4j:configuration>
Notice the usage of Filter class in the console appender. Below is a simple
class doing basic logging.
package com.journaldev.log4j.main;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;
public class Log4jExample
static
init();
private final static Logger logger = Logger.getLogger(Log4jExample.class);
public static void main(String args)
Log4j Appenders
Pankaj Kumar
log4j Appender
This is the base of log4j Appenders that defines the methods to implement
by an appender.
log4j AppenderSkeleton
This class provides the code for common functionality, such as support for
threshold filtering and support for general filters. This is the base
implementation that is extended by all other appenders such as
JDBCAppender , AsyncAppender , ConsoleAppender etc. It has only
log4j.appender.file.Append=true
log4j.appender.file.ImmediateFlush=true
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d %dZ %-5p (%F:%L) %m%n
That's all for a quick roundup on log4j appenders.
Hungry for
More?
Head over to JournalDev to learn
more technologies with example
projects to download.
Check Out Now!