05 - log4j Examples

5.1 Overview

Let’s create a sample application using Eclipse so that we can run some sample program to use log4j.

5.2 Create a java project in Eclipse

To create a java project in eclipse, go to File à Newà Java Project (as shown below)

                Create Java Project In Eclipse

Enter the name of java project and click Finish. In this chapter, we have created project name as “log4j-Example” (refer below figure)

        Name the Java Project

Once done you will see the project created under Project explorer.

         java project inp project Explorer

5.3 Add log4j.jar in project

Now is the time to add the log4j jar file we have downloaded Chapter 3

  • Create a folder “lib” in java project created in Section 5.2. To do so

Right Click on Project à Newà Folder and give the name “lib”

          Create Folder For Java Project

Copy the log4j-1.2.17.jar files (from the downloaded log4j) and paste in lib folder

       Copy Jar files To Folder

We need to have these jar files in build path (class path) .To do so Select all the jar files and

Right Click à Build Pathà Add to Build Path (refer below figure)

         Add Jar Files To Build Path

5.4 log4j Examples

Let’s write some examples to see what we have discussed so far in earlier chapters.

5.4.1 Example1 – Using Basic Configurator

Using a BasicConfigurator is the simplest way to use the log4j in application. Lets create a TestBasicConfigurator.java file 

package com.log4j.examples;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class TestBasicConfigurator {

   static Logger logger = Logger.getLogger(TestBasicConfigurator.class);

   public static void main(String[] args) {

   BasicConfigurator.configure();

   logger.error(" ERROR Log Message!!! ");
   logger.info(" INFO Log Message!!! ");
   logger.debug(" DEBUG Log Message!!! ");
   logger.fatal(" FATAL Log Message!!! ");
   }
}

Running the above program will print the log statements on console.

0 [main] ERROR com.log4j.examples.TestBasicConfigurator  -  ERROR Log Message!!! 
0 [main] INFO com.log4j.examples.TestBasicConfigurator  -  INFO Log Message!!! 
0 [main] DEBUG com.log4j.examples.TestBasicConfigurator  -  DEBUG Log Message!!! 
0 [main] FATAL com.log4j.examples.TestBasicConfigurator  -  FATAL Log Message!!! 

5.4.2 Example2 – Using log4j.properties

Let’s write a log4j.properties file to log messages on console. To do this

  1. Create a log4j.properties file in src folder with below content.
log4j.rootLogger=DEBUG,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss}%-5p%c{1}:%L-%m%n

  b. Create a TestProgram TestLog4jProperties.java

package com.log4j.examples;
import org.apache.log4j.Logger;

public class TestLog4jProperties {

   static Logger logger = Logger.getLogger(TestLog4jProperties.class);
   public static void main(String[] args) {

   logger.error(" ERROR Log Message!!! ");
        logger.info(" INFO Log Message!!! ");
        logger.debug(" DEBUG Log Message!!! ");
        logger.fatal(" FATAL Log Message!!! ");
    }
}

    c. Running the TestLog4jProperties.java program will have below output.

2015-04-26 22:35:30 ERROR TestLog4jProperties:12 -  ERROR Log Message!!! 
2015-04-26 22:35:30 INFO  TestLog4jProperties:13 -  INFO Log Message!!! 
2015-04-26 22:35:30 DEBUG TestLog4jProperties:14 -  DEBUG Log Message!!! 
2015-04-26 22:35:30 FATAL TestLog4jProperties:15 -  FATAL Log Message!!! 

Update the program to write log statements in file instead of console. To do so update  log4j.properties as below.

log4j.rootLogger=DEBUG, file
# Direct log messages to a file
log4j.appender.file=org.apache.log4j.RollingFileAppender

# log file path with name
log4j.appender.file.File=C:\\test\\logs.log

# max size of log file, after this a new file will be created
log4j.appender.file.MaxFileSize=10MB

# max number of log files 
log4j.appender.file.MaxBackupIndex=10

# layouts
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss} %-5p %c{1}:%L - %m%n

Running the program will create a file logs.log with below output

2015-04-26 22:39:22 ERROR TestLog4jProperties:12 -  ERROR Log Message!!! 
2015-04-26 22:39:22 INFO  TestLog4jProperties:13 -  INFO Log Message!!! 
2015-04-26 22:39:22 DEBUG TestLog4jProperties:14 -  DEBUG Log Message!!! 
2015-04-26 22:39:23 FATAL TestLog4jProperties:15 -  FATAL Log Message!!!

5.4.3 Example3 – Using log4j.xml

Let’s write a log4j.xml file to log messages on console. To do this

  1. Create a log4j.xml file in src folder with below content.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
    xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
      <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" 
        value="%d{yyyy-MM-ddHH:mm:ss} %-5p %c{1}:%L - %m%n" />
      </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

   b. Create a TestProgram TestLog4jXML.java

package com.log4j.examples;

import org.apache.log4j.Logger;
public class TestLog4jXML{

   static Logger logger = Logger.getLogger(TestLog4jXML.class);

   public static void main(String[] args) {

        logger.error(" ERROR Log Message!!! ");
        logger.info(" INFO Log Message!!! ");
        logger.debug(" DEBUG Log Message!!! ");
        logger.fatal(" FATAL Log Message!!! ");
    }
} 

Running the program will print below statements 

log4j: reset attribute= "false".
log4j: Threshold ="null".
log4j: Level value for root is  [ERROR].
log4j: root level set to ERROR
log4j: Class name: [org.apache.log4j.ConsoleAppender]
log4j: Parsing layout of class: "org.apache.log4j.PatternLayout"
log4j: Setting property [conversionPattern] to [%d{yyyy-MM-ddHH:mm:ss} %-5p %c{1}:%L - %m%n].
log4j: Adding appender named [console] to category [root].
2015-04-26 22:46:29 ERROR TestLog4jXML:12 -  ERROR Log Message!!! 
2015-04-26 22:46:29 INFO  TestLog4jXML:13 -  INFO Log Message!!! 
2015-04-26 22:46:29 DEBUG TestLog4jXML:14 -  DEBUG Log Message!!! 
2015-04-26 22:46:29 FATAL TestLog4jXML:15 -  FATAL Log Message!!!

Update the program to write log statements in file instead of console. To do so update log4j.xml as below.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
    xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="file" class="org.apache.log4j.RollingFileAppender">
    <param name="append" value="false" />
    <param name="maxFileSize" value="10KB" />
    <param name="maxBackupIndex" value="5" />
    <param name="file" value="C:/test/logs.log" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" 
            value="%d{yyyy-MM-ddHH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
    </appender>

   <root>
        <level value="DEBUG" />
        <appender-ref ref="file" />
    </root>

</log4j:configuration>

Running the program will log below statements in logs.log file

2015-04-26 22:47:40 ERROR TestLog4jXML:12 -  ERROR Log Message!!! 
2015-04-26 22:47:40 INFO  TestLog4jXML:13 -  INFO Log Message!!! 
2015-04-26 22:47:40 DEBUG TestLog4jXML:14 -  DEBUG Log Message!!! 
2015-04-26 22:47:40 FATAL TestLog4jXML:15 -  FATAL Log Message!!!

5.4.4 Example4 – Configure Dynamic paths/values

In earlier examples, we have hard-coded the name and path of log file but quite often we want to keep the log file path or name dynamic so we can use same log4j.xml or log4j.properties file in other environments.

To achieve this, we can use the dynamic values like ${log.file.path} and pass the value at run time. We can use any variable name. To pass the value at run time, we have got two options –

  1. Use System.setProperty(“variable-name”,”variable value”); in code but make sure we are setting this before creating the logger object.
  2. Run java program with –Dvariable-name=variable-value  arguments.

Lets update the log4j.xml file to use variables for file name.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
    xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="file" class="org.apache.log4j.RollingFileAppender">
    <param name="append" value="false" />
    <param name="maxFileSize" value="10KB" />
    <param name="maxBackupIndex" value="5" />
    <param name="file" value="${log.file.path}" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" 
            value="%d{yyyy-MM-ddHH:mm:ss} %-5p %c{1}:%L - %m%n" />
    </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="file" />
    </root>

</log4j:configuration>

Update the jave code as below to set the value of variable. We have set it in static initializer so that it gets set before the creation of logger object.

package com.log4j.examples;

import org.apache.log4j.Logger;

public class TestLog4jXML {

   static{
    System.setProperty("log.file.path","C:/test/logs1.log")    ;
    }
    static Logger logger = Logger.getLogger(TestLog4jXML.class);

    public static void main(String[] args) {

        logger.error(" ERROR Log Message!!! ");
        logger.info(" INFO Log Message!!! ");
        logger.debug(" DEBUG Log Message!!! ");
        logger.fatal(" FATAL Log Message!!! ");
    }
}

Running the above program will log in logs1.log

5.4.5 Example 5- Use Property Configurator

If we want to use custom property file instead of log4j.properties file, then we can use PropertyConfigurator.

Let’s create a custom.properties file as below in C:\\test directory

log4j.rootLogger=INFO,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss}%-5p%c{1}:%L-%m%n

Create java program to use custom.properties file as below

package com.log4j.examples;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Test {

static Logger logger = Logger.getLogger(Test.class);
public static void main(String[] args) {

PropertyConfigurator.configure("C:/test/custom.properties");
        logger.error(" ERROR Log Message!!! ");
        logger.info(" INFO Log Message!!! ");
        logger.debug(" DEBUG Log Message!!! ");
        logger.fatal(" FATAL Log Message!!! ");
    }
}

Running above program will load the configuration from custom.properties file and will print below statements

2015-04-26 23:14:55 ERROR Test:15 -  ERROR Log Message!!! 
2015-04-26 23:14:55 INFO  Test:16 -  INFO Log Message!!! 
2015-04-26 23:14:55 FATAL Test:18 -  FATAL Log Message!!! 

5.4.6 Example 6 -Define Custom Logger

In all above examples, we have used root logger only but as we discussed in earlier chapters, we can configure the different properties for different loggers also.

To define a properties for a specific logger, we need to use tags like below

<logger name="com.test">
  <level value="ERROR"/>
  <appender-ref ref="console" />
</logger>

Above tag says the for a logger com.foo, configure the log level as Error and appender as console.

Note: Add these tab above <root> tag

Let’s write an example where Root logger is configured as DEBUG level where as custom logger as ERROR so for custom logger messages above ERROR or ERROR severity will be logged but for all other classes , it will log DEBUG statements also.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
    xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
      <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" 
        value="%d{yyyy-MM-ddHH:mm:ss} %-5p %c{1}:%L - %m%n" />
      </layout>
    </appender>

    <logger name="com.log4j.examples.Test">
        <level value="ERROR"/>
        <appender-ref ref="console" />    
    </logger>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

Create test program 

package com.log4j.examples;

import org.apache.log4j.Logger;

public class Test {

      static Logger logger = Logger.getLogger(Test.class);
      public static void main(String[] args) {
      ogger.error(" ERROR Log Message!!! ");
      logger.info(" INFO Log Message!!! ");
      logger.debug(" DEBUG Log Message!!! ");
      logger.fatal(" FATAL Log Message!!! ");
    }
}

Running above program will log only ERROR and FATAL messages but it will be displayed twice because Root logger is also defined and all loggers inherits Root logger.

You can delete the <root> tag to remove the Root logger but in this case all other loggers which are not defined in log4j.xml will stop logging because Root logger is also removed.

Alternatively and recommendation is to use the additvity flag and set it to false so that logger will not inherit anything from Root. To do so use below 

<logger name="com.log4j.examples.Test"  additivity="false">
   <level value="ERROR"/>
   <appender-ref ref="console" />
</logger>

Like us on Facebook