Pages

Quick Guide to Java logging | log4j


Logging is a very important feature of any software. You could see the problem in your software through logs, trace the error, fix them etc. It is not only helpful in the development phase but in the Production as well.
If the logging module is not properly planned, in an enterprise software, it could cause all sorts of disadvantages.

Log4j is one of the most used logging api for java.

The various components of Log4j are
1. Loggers
These are hierarchical. For example com.abc and com.abc.def will have different hierarchy of log when you pass their class names while instantiating the logger. In the configuration file, you could configure particular module to one level of logging while the Root to the other, with the hierarchy.

static Logger log = LogManager.getLogger(LogTest.class.getName());

2. Appenders
Console appenders, File appenders, database appenders and more. Appenders define where the output will be. Appenders needs to be registered in a Logger. Then any log message in the logger is forwarded to all the appenders.

3. Layouts
This is responsible for formatting the log messages.
Pattern layout, html layout etc. You can have your own formator or you could simply use Pattern layout and append timestamp, etc in the front of the log message.

4. Priorities
(DEBUG < INFO < WARN < ERROR < FATAL)

5. Configuration
(log4j 2+ will find log4j.xml in the classpath). You could configure it through the code, but its a good idea to configure it through xml's or jsons. It could also auto renew the configuration when the configuration file is changed, without having to recompile or restart the application.

An Example of the log4j.xml file
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorinterval="30">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="File1" fileName="output.log">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    
    <Loggers>
        <logger name="tutorials.LogTest" level="TRACE" additivity="false" >
            <AppenderRef ref="Console"/>
        </logger>
        <Root level="debug">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File1"/>
        </Root>
    </Loggers>
</Configuration>

The Logger is configure to refresh its settings every 30 seconds. There are two appenders, console and File.
The root logger is set to level debug, and both the appenders are registered to it. However for the class tutorials.LogTest, its level is Trace and so its TRACE messages will also be logged. The additivity=false code will prevent any duplicate logging(when the appenders are registered to it as well).

The Example of using the Logger
package tutorials;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @author Rajan Prasad Upadhyay
 */
public class LogTest {

    static Logger log = LogManager.getLogger(LogTest.class.getName());

    public static void main(String[] args) {
        log.trace("Trace Message!");
        log.debug("Debug Message!");
        log.info("Info Message!");
        log.warn("Warn Message!");
        log.error("Error Message!");
        log.fatal("Fatal Message!");
    }
}

No comments:

Post a Comment

If you like to say anything (good/bad), Please do not hesitate...