09 - log4j Appenders

9.1 Overview

Log4j comes with several built in appendersand allows us to create our own appendersalso. The appendertells the destination of the logs. Log4j also supports asynchronous logging which does not block the users thread for logging activity.The parent of all appenders areAppender and it comes under org.apache.log4j package and is an interface.

9.2 AppenderAdditivity

By default, appenders are inherited from the parent logger’s appender and we can add more appender at a child logger. In other words, if a parent logger (“com”)  is configured to use Console Appender, then child logger (“com.test”) gets Console appender by default and it can configure add more appender if needed.

9.2.1 Additivity Flag

We can turn off the additivity so that parent logger’s appender does not get inherited at a child logger by simply set the appender–additivity flag to false.

Since Root logger is the parent of all loggers, additivity is not applicable on Root logger.

Lets discuss some scenarios for appenderadditivity.

  1. If Root logger is configured to use Appender A1 then it all logs statements will be directed to A1 destination.
  2. Logger with name “com” configured to use Appender A2, then all logs statements will be directed to A1 and A2 destination ( appenders of both Root and “com”)
  3. Logger with name “xyz” has not configured any  Appender, then all logs statements will be directed to A1( appenders of Root)
  4. Logger with name “com.test” configured to use Appender A3, then all logs statements will be directed to A1, A2  and A3 destination ( appenders of Root, “com” and “com.test”)
  5. Logger with name “abc” configured to use Appender A4 and set the additivity as false, then all logs statements will be directed to A4 destination only ( appenders of “abc”)
  6. Logger with name “abc.zyz” has not configured any appeender and  set the additivity as true, then all logs statements will be directed to A4 destination only ( appenders of “abc”)

9.3 Built-In Appenders

Log4j comes with several useful built-in appenders to send the logs to different types of destinations like email, files, console, JMS ,JDBCetc. Lets have a look at some of them.

  1. ConsoleAppender- ConsoleAppender is used to log the messages on console. We can configure the console appender in a configuration file or in xml like below-

<appender name="console" class="org.apache.log4j.ConsoleAppender">

       <layout class="org.apache.log4j.xml.XMLLayout">

       </layout>

       </appender>

  1. FileAppender- As its name suggests,FileAppender logs the messages in files. There are several options available which can be used to configure the FileAppender. Some of them are-
  • File – to specify the path of file with name. We can also specify the variables like "${log.file.path} which will be replaced with the value of log.file.pathSystem variable.
  • bufferedIO- default value is false and it controls the buffered output.
  • bufferSize- size of buffer if bufferedIO is set to true.
  1. RollingFileAppender-RollingFileAppender extends FileAppender and allows us to configure the maximum size of a file and maximum number backup files. All the properties available in FileAppenderis available in RollingFileAppender also. In addition to those the two important properties are-
  • maxFileSize – the max size of the log file after which it will be rolled.
  • maxBackupIndex- this property is used to configure the maximum number of backups.
  1. DailyRollingFileAppender-DailyRollingFileAppender extends FileAppender and it automatically rolls the file on midnight by default. However we can configure the pattern on which it should roll out the log file. All the properties available in FileAppenderis available in RollingFileAppender also.
  • DatePattern- We can use DatePattern specify the pattern to schedule the rollover of log files. For example ‘.’yyyy-MM denotes that file should be logged at the beginning of every month and '.' yyyy-MM-dd-HH schedules hourly rolling over of log files.
  1. JDBCAppender- JDBCAppender is used to store the log information in the database.There are several properties available for JDBCAppender which need to be used to configure the database details.
  • Driver – to configure the database driver
  • Password- to configure the database password.
  • User- to configure the username of database.
  • URL- to configure the URL of database
  • Sql- to specify the sql statement which will be executed internally on every log statement.

9.5 Examples –

Lets write some example using the appenders.

9.5.1 – ConsoleAppender

a. 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>

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

</log4j:configuration>

b. Write a program to log messages

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) {

        logger.debug("Debug message ...");
        logger.error("Error message ... ");
        logger.fatal("fatal message ... ");
        logger.info(" Info message ... ");
        logger.trace(" trace message...");    
    }
}

c. On Running above program, below statements will be printed on console.

2015-05-02 18:34:09 DEBUG Test:15 - Debug message ...
2015-05-02 18:34:09 ERROR Test:16 - Error message ... 
2015-05-02 18:34:09 FATAL Test:17 - fatal message ... 
2015-05-02 18:34:09 INFO  Test:18 -  Info message ... 

 

9.5.2 – RollingFileAppender

a. Create a log4j.xml in src folder with below content. We configure the maximum file size as 2KB and maxBackupIndex as 5.

<?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="2KB" />
       <param name="maxBackupIndex" value="5" />

       <param name="file" value="D:\\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="INFO" />
        <appender-ref ref="file" />
    </root>

</log4j:configuration>

b. Write a program to log messages.

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) {

        {
        logger.debug("Debug message ...");
        logger.error("Error message ... ");
        logger.fatal("fatal message ... ");
        logger.info(" Info message ... ");
        logger.trace(" trace message...");        
        }    

   }
}

 c.  On Running above program, logs.log, logs.log.1, logs.log.2, logs.log.3,logs.log.4,logs.log.5 gets created and with size of 2KB.

Like us on Facebook