Friday, September 6, 2019

Log4J 2 Configuration

Earlier we have learn about Log4j configurations in details. Here we will learn about configuration of Log4j 2 configuration in maven project.

Step 1:

Create a maven project(we can create a simple java project as well).

Step 2:

Add dependency in pom.xml file.


        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.12.1</version>
        </dependency>


        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.12.1</version>
        </dependency>


Step 3:

Create Log4j2 configuration xml file if it is not created then only error will be displayed on console.


<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="logPath">./logs</Property>
        <Property name="rollingFileName">testlog</Property>
        <Property name="consolePattern"> %d{DEFAULT} [%t] [%highlight{%-5level}] %c:%L:%F - %msg%n%throwable{short.lineNumber}</Property>
        <Property name="rollingFilePattern">%d{DEFAULT} [%t] [%highlight{%-5level}] %c:%L:%F - %msg%n%throwable{short.lineNumber}</Property>
    </Properties>

    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout
                pattern="${consolePattern}" />
        </Console>

        <RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}-%i.log">
            <PatternLayout
                pattern="${rollingFilePattern}" />
            <Policies>
                <!-- Causes a rollover if the log file is older than the current JVM's start time -->
                <!-- <OnStartupTriggeringPolicy /> -->
                <!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
                <!-- <TimeBasedTriggeringPolicy interval="1" modulate="true" /> -->
                <SizeBasedTriggeringPolicy size="10 mb" />
            </Policies>
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>

        <RollingFile name="htmlFileLogger" fileName="${logPath}/${rollingFileName}.html" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}-%i.html">
            <HTMLLayout charset="UTF-8" title="Test Logs" locationInfo="true" />
            <Policies>
                <!-- <TimeBasedTriggeringPolicy interval="1" modulate="true" /> -->
                <SizeBasedTriggeringPolicy size="10 mb" />   
            </Policies>
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>

    </Appenders>
    <Loggers>
        <Root level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
            <AppenderRef ref="rollingFile" />
            <AppenderRef ref="htmlFileLogger" />
        </Root>
    </Loggers>
</Configuration>


Step 4:

We can put this configuration file in classpath of the created project but if we try to keep the different location then we need to mention the path of this configuration file set this file location on LoggerContext.

        LoggerContext context = (LoggerContext) LogManager.getContext(false);
        File file = new File("./log4j2.xml");
        context.setConfigLocation(file.toURI());


Step 5:

Now we can write the following code for logging using Log4j2.

import java.io.File;
import java.io.IOException;

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



public class TestLogger {

    private static final Logger logger = LogManager.getLogger(TestLogger.class.getName());
   
    public static void main(String args[]) throws IOException {
        LoggerContext context = (LoggerContext) LogManager.getContext(false);
        File file = new File("./log4j2.xml");
        context.setConfigLocation(file.toURI());
        for (int i = 0; i < 100; i++) {
            logger.info("Test" + i);
            logger.error("Test" + i);
            logger.debug("Test" + i);
            logger.warn("Test" + i);
        }
    }


Step 6: 

Complete project structure should be looked like below: