Log4j 2 Properties Configuration with Console Appender
Tags: Log4j Apache Log4j 2 log4j-api log4j-core log4j LogManager log4j Logger log4j properties
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 Properties 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 Properties configuration to log to Console
Adding /src/main/resources/log4j2.properties to your project
status = error
name = ConsoleExample
packages = simplesolution.dev
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d - %t - %p - %c - %m%n
rootLogger.level = trace
rootLogger.appenderRef.stdout.ref = STDOUT
Example code to log messages
package simplesolution.dev;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4j2PropertiesConfigurationConsoleExample {
private static final Logger logger = LogManager.getLogger(Log4j2PropertiesConfigurationConsoleExample.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-08 01:14:06,494 - main - TRACE - simplesolution.dev.Log4j2PropertiesConfigurationConsoleExample - Trace message
2019-05-08 01:14:06,503 - main - INFO - simplesolution.dev.Log4j2PropertiesConfigurationConsoleExample - Info message
2019-05-08 01:14:06,503 - main - DEBUG - simplesolution.dev.Log4j2PropertiesConfigurationConsoleExample - Debug message
2019-05-08 01:14:06,504 - main - WARN - simplesolution.dev.Log4j2PropertiesConfigurationConsoleExample - Warn message
2019-05-08 01:14:06,504 - main - ERROR - simplesolution.dev.Log4j2PropertiesConfigurationConsoleExample - Error message
2019-05-08 01:14:06,504 - main - FATAL - simplesolution.dev.Log4j2PropertiesConfigurationConsoleExample - Fatal message
Download Source Code
The source code in this article can be found at: https://github.com/simplesolutiondev/Log4j2PropertiesConfigurationConsole
Happy Coding 😊