Log4j

Every big applications have some sort of logging facilities or tracing API. Logging is necessity, rather than just another feature. Here I would like to talk about Log4j logger. It is not perfect but good enough for all kind of applications and business scale.

How to install log4j

  • Download stable release from internet.
  • In GUI, just import log4j-x.x.x.jar file to project library.
  • In web, place log4j property file at server domain location or at project source directory
  • In WAR module, include following code at pom.xml file.


Add following lines at pom.xml. Log4j has three other dependencies, so these dependencies can be removed by <exclusions> tag. If you need these dependencies just don’t add all <exclusions> tag part.

<dependency>
<groupid>log4j</groupid>
<artifactid>log4j</artifactid>
<version>1.2.15</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactid>jms</artifactid>
<groupid>javax.jms</groupid>
</exclusion>
<exclusion>
<artifactid >jmxri</artifactId>
<groupid>com.sun.jmx</groupid>
</artifactid></exclusion>
<exclusion>
<artifactid>jmxtools</artifactid>
<groupid>com.sun.jdmk</groupid>
</exclusion>
</exclusions>
</dependency>

How to configure?
Configuring part is important and sometime really troublesome. We can configure log4j in two ways : log4j.xml and log4j.properties.
First for simple start, just create a properties file with name log4j. I will be talking more about log4j.properties here, because it’s simple and easy to pick up with. But that don’t mean log4j.xml isn’t useful. XML format log4j is more suited for complex, big projects and provides better features that properties format. Let’s start –
A simple log4j.properties configuration will look like something this :

# The default root appender
log4j.rootLogger=A1

# A1 is set to be a ConsoleAppender which outputs to System.out.
log4j.appender.A1=org.apache.log4j.FileAppender
log4j.appender.A1.file=app.log
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-22d{dd/MMM/yyyy HH:mm:ss} %-8p %c [%t] - %m (%l)%n

# An extra category to a log file
log4j.category.AppLogging=A2

# A3 is set to be a FileAppender which will log all actions in the application.
log4j.appender.A3=org.apache.log4j.FileAppender
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=%-22d{dd/MMM/yyyy HH:mm:ss} - %m%n
log4j.appender.A3.file=application.log

log4j.additivity.AppLogging=false

Leave a comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.