06 - log4j API

6.1 Overview

In this chapter we will discuss the most commonly used API or we can say the methods of log4j.The main class for log4j is Logger which is available under org.apache.log4j package.

Lets have a look at the methods.

6.2 Logger Creation

As we discussed in previous chapters the first task for logging is to obtain a logger object. Logger class supports two static methods to obtain a Logger object.

  1. public static Logger getRootLogger(); - This API is used to obtain the Root Logger
  2. public static Logger getLogger(String loggerName);-  This API needs to be used to obtain a logger object of a given name. We can use any String as a logger name however it’s a good practice to use the fully qualified class name as logger name if you are defining a specific logging behaviour for each class.

Calling getLogger() method with same name will return the same logger instance which means below two loggers (“abc” and “xyz” are referring to same logger instance).

Logger abc= Logger.getLogger(“com.test”);

Logger xyz= Logger.getLogger(“com.test”);

6.3 Log Methods

There are several methods available in logger class to log the messages and they are related to the log levels.

There are around six methods available corresponding to six log levels.

  1. public void debug(Object message)-This method is used to print the log message with the DEBUG log level. These messages will only log if configuration is set to DEBUG of above.
  2. public void error(Object message)- This method is used to print the log message with the ERROR log level. These messages will only log if configuration is set to ERROR of above.
  3. public void fatal(Object message)-This method is used to print the log message with the FATAL log level. These messages will only log if configuration is set to FATAL of above.
  4. public void info(Object message)-This method is used to print the log message with the INFO log level. These messages will only log if configuration is set to INFO of above.
  5. public void warn(Object message)-This method is used to print the log message with the WARN log level. These messages will only log if configuration is set to WARN of above.
  6. public void trace(Object message)-This method is used to print the log message with the TRACE log level. These messages will only log if configuration is set to TRACE of above.

6.4 Other Utility Methods

There are several others utility methods available which can be used to know the configurations or do the configurations programmatically.

  1. publicbooleangetAdditivity() – This method can be used to get the value of additivity flag of this logger.
  2. public void setAdditivity(boolean additive)- This method can be used to set the value of additivity flag of this logger.
  3. public Enumeration getAllAppenders()– This method can be used to get all the configured appender of this logger.In case no appender is configured, this API will return null.
  4. public AppendergetAppender(String name) – This method can be used to get the appender of the given name
  5. public void setLevel(Level level)- This method can be used to set the logging level of a logger.
  6. public final Level getLevel()-This method can be used to get the configured logging level of a logger.
  7. public void addAppender(AppendernewAppender) – This method can be used to add a new appender in the list of already configured appenders of the logger.
  8. publicbooleanisDebugEnabled() – This method can be used to check if debug log level is enabled for this logger or not.
  9. publicbooleanisInfoEnabled() – This method can be used to check if info log level is enabled for this logger or not.
  10. publicbooleanisEnabledFor(Priority level)- This is a generic method to verify if the given log level is enabled or not.

6.5 Example

Lets write an example to use some of the above APIs

  1. Create a log4j.xml 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>

    <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="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>

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

</log4j:configuration>

 b. Create a Test program 

package com.log4j.examples;

importjava.util.Enumeration;
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Test {

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

   booleanadditivity = logger.getAdditivity();
   System.out.println("Additivity :" + additivity);
   Level level = logger.getLevel();

   System.out.println("Log Level:" + level):
   System.out.println("Debug Log Level Enabled ?" + logger.isDebugEnabled());

   Enumeration<Appender>appenders = logger.getAllAppenders();

   while(appenders.hasMoreElements())
   {
     Appenderappender= appenders.nextElement();
     System.out.println("Appender Name:" +appender.getName());
     System.out.println("Appender Class:" + appender.getClass());
     System.out.println("---------------------");    
    }

    logger.debug("Debug message not printed");
    logger.error("Error message printed");

  }
} 

c. Running a Test program will produce below output

Additivity :false
Log Level:ERROR
Debug Log Level Enabled ?false
AppenderName:console
AppenderClass:class org.apache.log4j.ConsoleAppender
---------------------
AppenderName:file
AppenderClass:class org.apache.log4j.RollingFileAppender
---------------------
2015-04-27 21:57:03 ERROR Test:43 - Error message printed

Like us on Facebook