Log4j 2 XML Configuration with Console Appender
Tags: Log4j Apache Log4j 2 log4j-api log4j-core log4j LogManager log4j Logger log4j xml
Java Code Examples for using
- org.apache.logging.log4j.LogManager
- org.apache.logging.log4j.Logger
The Java code example below to show you how to configure Log4j 2 with XML configuration file to log messages to sytem console using Console appender.
Adding Log2j 2 Dependencies to your project
Add dependencies below to your build.gradle if you are using Gradle build.
dependencies {
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.11.2'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.11.2'
}
Add dependencies below to your pom.xml if you are using Maven build.
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.2</version>
</dependency>
Example XML configuration to log to Console
Adding /src/main/resources/log4j2.xml to your project
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error" name="ConsoleExample" packages="simplesolution.dev">
<Appenders>
<Console name="STDOUT">
<PatternLayout pattern="%d - %t - %p - %c - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="STDOUT" />
</Root>
</Loggers>
</Configuration>
Example code to log messages
package simplesolution.dev;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4j2XMLConfigurationConsoleExample {
private static final Logger logger = LogManager.getLogger(Log4j2XMLConfigurationConsoleExample.class.getName());
public static void main(String... args) {
logger.trace("Trace message");
logger.info("Info message");
logger.debug("Debug message");
logger.warn("Warn message");
logger.error("Error message");
logger.fatal("Fatal message");
}
}
Application output:
2019-05-07 21:32:31,111 - main - TRACE - simplesolution.dev.Log4j2XMLConfigurationConsoleExample - Trace message
2019-05-07 21:32:31,121 - main - INFO - simplesolution.dev.Log4j2XMLConfigurationConsoleExample - Info message
2019-05-07 21:32:31,122 - main - DEBUG - simplesolution.dev.Log4j2XMLConfigurationConsoleExample - Debug message
2019-05-07 21:32:31,122 - main - WARN - simplesolution.dev.Log4j2XMLConfigurationConsoleExample - Warn message
2019-05-07 21:32:31,122 - main - ERROR - simplesolution.dev.Log4j2XMLConfigurationConsoleExample - Error message
2019-05-07 21:32:31,123 - main - FATAL - simplesolution.dev.Log4j2XMLConfigurationConsoleExample - Fatal message
Download Source Code
The source code in this article can be found at: https://github.com/simplesolutiondev/Log4j2XMLConfigurationConsole
Happy Coding 😊