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:

 

7 comments:

  1. Hello Arjun,

    Can you please give the detail explanation of Step 4??

    ReplyDelete
    Replies
    1. 1. By default Log4j 2 try to find the configuration file of log4j from class path so we make it as false
      LoggerContext context = (LoggerContext) LogManager.getContext(false);

      2. Now passing the configuration file for log4j.
      File file = new File("./log4j2.xml");
      context.setConfigLocation(file.toURI());

      Delete
  2. Hi Arjun,

    How to generate logs in both html and log file?

    Thanks!

    ReplyDelete
    Replies
    1. It is already generating html and and normal log file because we are using html appender in config

      Delete
  3. public class UdemyTest extends BrowserSetup {

    WebDriver driver;
    SearchWebDevelopement obj;
    public static Logger log=LogManager.getLogger(UdemyTest.class);
    @BeforeTest
    public void setup() throws IOException
    {
    driver=initializeDriver();
    log.info("driver is initialized");
    driver.get("https://www.udemy.com/");
    log.info("Navigated to homepage");
    UdemyPagesFunctionality ob=new UdemyPagesFunctionality(driver);
    ob.maximizeWindow(driver);
    }
    @Test
    public void CorrectSearchWeb()
    {
    SearchWebDevelopement obj=new SearchWebDevelopement(driver);
    obj.Search("web developement");
    boolean status=driver.findElement(By.xpath("//select[@name='sort']")).isDisplayed();
    Assert.assertTrue(status);
    // System.out.println("Correct course searched");
    log.info("Successfully validated text message");
    }



    I am not able to generate the logger file even after adding dependencies and log4j2.xml

    ReplyDelete
  4. I have added log4j2.xml and TestLogger.java class accordingly, still if I do maven install my cucumber-report is generating the error
    'Error: no log4j2 configuration file found' can u give any advice here please

    ReplyDelete