How to Configure Log4j in your project (Using Log4j.xml file)?
(To learn about how logging can be achieved using log4j.properties file, click here– )
<?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="consoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n"/>
</layout>
</appender>
<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
<param name="append" value="false"/>
<param name="file" value="out/learning.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n"/>
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="consoleAppender"/>
<appender-ref ref="fileAppender"/>
</root>
</log4j:configuration>
If you want to provide the max size, we can add below statement as param to RollingFileAppender.
<param name="maxFileSize" value="1MB" />
<param name="MaxBackupIndex" value="2"/>
Logger log = Logger.getLogger("your_class_name")
Below sample code shows how can we log the information for various logging level.
package com.aayushCorp.appData.tests;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class LoggerExampleTest {
public static void main(String[] args) {
Logger log = Logger.getLogger("LoggerExampleTest");
WebDriver driver = new FirefoxDriver();
driver.navigate().to("https://www.google.co.in");
log.info("This is Info message - Launched Google");
log.debug("This is debug message");
log.error("This is error message");
log.fatal("This is fatal mesage");
log.trace("This is trace message");
driver.close();
}
}
Run the program, you will see below output.
INFO [main] (LoggerExampleTest.java:16)- This is Info message - Launched Google
DEBUG [main] (LoggerExampleTest.java:17)- This is debug message
ERROR [main] (LoggerExampleTest.java:18)- This is error message
FATAL [main] (LoggerExampleTest.java:19)- This is fatal mesage
TRACE [main] (LoggerExampleTest.java:20)- This is trace message
Based on Log4j.xml file, log messages will be stored in .log file (text file) at the defined path on xml file.