log4j Tutorial - Log4j Installation








Log4j API package is distributed under the Apache Software License.

The latest log4j version, including full-source code, class files and documentation can be found at http://logging.apache.org/log4j/.

We can download apache-log4j-x.x.x.tar.gz or the zip file from the link above.

Supporting Library

We can use log4j to log information to various destinations, such as sending out email, to database, or to a file.

There are a list of libraries we need to put to classpath so that log4j can pick it up and use it.

For example, when sending out email from log4j we need the email library jar file.

The libraries are optional and depend on what features we are going to use with log4j framework.

  • JavaMail API (mail.jar): from https://glassfish.dev.java.net/javaee5/mail/ for e-mail based logging.

  • JavaBeans Activation Framework(activation.jar): from http://java.sun.com/products/javabeans/jaf/index.jsp.

  • Java Message Service: for JMS and JNDI.

  • XML Parser(Xerces.jar): from http://xerces.apache.org/xerces-j/install.html.





Maven and Log4j

First, use the following maven command to create an empty Maven project.

C:\mvn_test>mvn archetype:generate -DgroupId=com.java2s.ide -DartifactId=MyTest -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Then, goes to the project folder and find the pom.xml, add the following dependency.

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

After that, add the following code to the log4j.properties which is created under the resources folder.

  
MyTest
 |
 +-src
    |
    +-main
       |
       +-java
       |  |
       |  +-com
       |    |
       |    +-java2s
       |       |
       |       +-ide
       |
       +-resources
          |
          +- log4j.properties         
            
  

As shown in the folder structure above the resources is located in the save level of java folder.

For Java web applications, store the log4j.properties file under the WEB-INF/classes directory

Save the following configuration into the log4j.properties file.

# Root logger option
log4j.rootLogger=DEBUG, stdout, file
 
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
 
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\log4j.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

The last %m%n configures the log4j to add line break.

%L sets the line number from where the logging request.

%c{1} references the logging name set via getLogger().

%-5p sets the logging priority, like DEBUG or ERROR.

Finally add the following code the App.java and run the application.

package com.java2s.ide;
 
import org.apache.log4j.Logger;
 
public class App{
 
  final static Logger logger = Logger.getLogger(App.class);
 
  public static void main(String[] args) {
 
    App obj = new App();
    obj.runMe("java2s");
 
  }
 
  private void runMe(String parameter){
 
    if(logger.isDebugEnabled()){
      logger.debug("This is debug : " + parameter);
    }
 
    if(logger.isInfoEnabled()){
      logger.info("This is info : " + parameter);
    }
 
    logger.warn("This is warn : " + parameter);
    logger.error("This is error : " + parameter);
    logger.fatal("This is fatal : " + parameter);
 
  }
 
}

The following code shows how to log an exception.

import org.apache.log4j.Logger;

public class App {

  final static Logger logger = Logger.getLogger(App.class);

  public static void main(String[] args) {

    App obj = new App();

    try {
      obj.divide();
    } catch (ArithmeticException ex) {
      logger.error("Sorry, something wrong!", ex);
    }
  }

  private void divide() {
    int i = 10 / 0;

  }

}