Signup/Sign In

Log4j2 with XML Configuration - Java Example

Posted in Programming   LAST UPDATED: AUGUST 18, 2021

    Learn how to use Log4j2 for logging in Java Application in this tutorial. Log4j2 with XML configuration provides a simple way of setting up logging in your Java application.

    Apache Log4j2 is the new version of the log4j and is used for printing logs when used in a Java program. In this tutorial we will setup a Maven project and use log4j2 to print logs from a simple Java class.

    If you are using Eclipse IDE, click on File > New > Project > Maven Project (You must have Maven Plugin installed in Eclipse for this)

    When asked for Group Id and Artifact Id, enter what you want, this will be used as name of the project and as package name for the Java project.

    Note: If you know how to setup a Maven Project, do it yourself.

    Once you are done, you should have a project structure similar to this,

    Using log4j2 for logging in Java

    Log4j2 Dependency in POM.xml

    To setup log4j2 for logging we will need log4j2 dependencies, which we will provide in our project's pom.xml file. Add the below code into your pom.xml file:

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

    The above code should be enclosed within the <dependencies> tag, if existing, add the above code to it, else create an opening and closing <dependencies> tag and add the above code in it.

    Log4j2 XML Configuration

    We will create an XML file to define the basic configurations for log4j like which appender to use Console appender, File appender etc and other setting like Pattern, log level etc.

    Now we will create an XML with name log4j2.xml and put it in the classpath, Log4j2 automatically looks for configuration files in the classpath. We will keep this in src/main/resource folder.

    To create this folder, right click on the project, go to New > Source Folder and provide the name src/main/resource:

    log4j2 example with XML configuration

    Now create a new file in this source folder with name log4j2.xml and add the following code to it:

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="WARN">
        <Appenders>
            <!-- Simple console logger --> 
            <Console name="LogToConsole" target="SYSTEM_OUT">
                <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger - %msg%n"/>
            </Console>
        </Appenders>
        <Loggers>
            <Logger name="com.abhishek.log4j2" level="debug" additivity="false">
                <AppenderRef ref="LogToConsole"/>
            </Logger>
            <Root level="error">
                <AppenderRef ref="LogToConsole"/>
            </Root>
        </Loggers>
    </Configuration>

    Change the package name as per your project. In the above configuration file we have specified the appender as Console appender, along with a PatternLayout to define the pattern of the log that will be printed.

    %d{HH:mm:ss.SSS} is used to add the timestamp along with specifying the format.

    [%t] will add the thread name to the log statement.

    %-5level will add the log level information to the log statement.

    %logger will add the fully qualified class name which is logging the log statement.

    %msg is for the log message and %n is for adding a new line after every log statement.

    Log4j2: Define the Logger and Log Level

    In the XML configuration file, we can specify the log level for the logger and can even set different log levels for different packages too.

    The root logger or the default logger is defined by the <Root> tag in the <Logger> tag,

    <Root level="error">
        <AppenderRef ref="LogToConsole"/>
    </Root>

    In the <AppenderRef> we will specify the name of the Console Appender defined in the <Appender> section above as the value for the ref attribute.

    We have specified the log level as error in the root logger. But we can specify different log level for different packages, like we have done by specifying this in our configuration XML:

    <Logger name="com.abhishek.log4j2" level="debug" additivity="false">
        <AppenderRef ref="LogToConsole"/>
    </Logger>

    Main Java Class

    Add the following code to the main Java class:

    package com.abhishek.log4j2;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    
    public class App {
    	
    	private static final Logger logger = LogManager.getLogger(App.class);
    
    	public static void main(String[] args) {
    
    		logger.debug("Hello from Log4j 2");
    		logger.debug("This is a Debug Message!");
    		logger.info("This is an Info Message!");
    		logger.error("And here comes the Error Message!", new RuntimeException("RunRunRun"));
    		
    	}
    
    }

    Change the code as per your project's package name etc.

    Once you are done with all this, right click on the main java class which is App.java in our case and run it as a Java Application. You should get the following output in console:


    21:37:12.458 [main] DEBUG com.abhishek.log4j2.App - Hello from Log4j 2
    21:37:12.464 [main] DEBUG com.abhishek.log4j2.App - This is a Debug Message!
    21:37:12.465 [main] INFO com.abhishek.log4j2.App - This is an Info Message!
    21:37:12.465 [main] ERROR com.abhishek.log4j2.App - And here comes the Error Message!
    java.lang.RuntimeException: RunRunRun
    at com.abhishek.log4j2.App.main(App.java:19) [classes/:?]

    Log4j2 File Appender: XML Configuration for Printing logs in File

    To print logs in a file rather than printing on console, we will use FileAppender instead of Console Appender in the XML configuraiton. Following is the XML configuration to print logs in a file with name app.log in the logs folder.

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="WARN">
        <Appenders>
        	<!-- Simple file logger -->
        	<File name="LogToFile" fileName="logs/app.log">
                <PatternLayout>
                    <Pattern>%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Pattern>
                </PatternLayout>
            </File>
        </Appenders>
        <Loggers>
            <Logger name="com.abhishek.log4j2" level="debug" additivity="false">
                <AppenderRef ref="LogToFile"/>
            </Logger>
            <Root level="error">
                <AppenderRef ref="LogToFile"/>
            </Root>
        </Loggers>
    </Configuration>

    As you can see that we have provided the filename and a pattern just like the console appender example above. We have also changes the value of the ref attribute in the <AppenderRef> tag in the <Logger> tag.

    Run the Java class again to check of the log file is getting created. You can even run the Java class multiple times and the logs will be appended in the same file.

    Using a File Appender and storing logs in a file helps in storing the logs for later analysis.

    But sometimes due to the amount of the logs being printed by an application the size of the log file can grow into MBs and even GBs, hence making it difficult for us to access and analyse the logs. To solve this problem we can use the RollingFile Appender.

    Log4j2 RollingFile Appender: XML Configuration for RollingFile

    Log4j2 RollingFile appender can be used to configure the Log4j2 to create new files by setting rules when to create a new file, this can either be a time related rule/policy of size related policy, for example, create a new log file every day or every hour or create a new log file once the size reaches say 10MB or 5MB.

    Use the following XML configuration for using RollingFile Appender.

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="WARN">
        <Appenders>
            <RollingFile name="LogToRollingFile" fileName="app-info.log" filePattern="app-info-%d{yyyy-MM-dd}.log">
                <PatternLayout>
                    <pattern>%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</pattern>
                </PatternLayout>
                <Policies>
                    <TimeBasedTriggeringPolicy interval="1" modulate="true" />
                    <SizeBasedTriggeringPolicy size="10 MB"/>
                </Policies>
            </RollingFile>
        </Appenders>
        <Loggers>
            <Logger name="com.abhishek.log4j2" level="debug" additivity="false">
                <AppenderRef ref="LogToRollingFile"/>
            </Logger>
            <Root level="error">
                <AppenderRef ref="LogToRollingFile"/>
            </Root>
        </Loggers>
    </Configuration>

    Conclusion:

    In this tutorial we saw how we can use Log4j2 with Java code to print logs on console, in a log file or even cerate rolling file for capturing logs from our Java application.

    You may also like:

    About the author:
    I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight
    Tags:Log4j2JavaLogging
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS