log4j2 Getting started with log4j2

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

This section provides an overview of what log4j2 is, and why a developer might want to use it.

It should also mention any large subjects within log4j2, and link out to the related topics. Since the Documentation for log4j2 is new, you may need to create initial versions of those related topics.

Why not Log4j 1.x?

Log4j 1.x is end-of-life as of August 5, 2015. [1][2]. Apache Log4j 2 is the successor to Log4j 1.x; provides bindings for projects that depend on Log4j 1.x, but wish to upgrade to Log4j 2. In addition to compatibility with Log4j 1.x, compatibility is provided for the SLF4J, Commons Logging, and java.util.logging APIs.

[1] https://logging.apache.org/log4j/1.2/
[2] https://blogs.apache.org/foundation/entry/apache_logging_services_project_announces

Installation or Setup

This would be a basic setup in wich we will send all the log messages to the console and to a log file.

Let's start with the libraries. Will use maven for that:

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

Next we'll write the log4j2.properties (I'll use a properties file in this case). We'll put it in the context path, in maven it should be in the resources folder (src/main/resources in most cases)

name=PropertiesConfig
property.filename = logs
appenders = console, file

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/propertieslogs.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

loggers=file
logger.file.name=com.es.form.studio
logger.file.level = debug
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
 

To use this example you'll need to change logger.file.name=com.es.form.studio so it targets the package of your choice. If you don't do that the file won't show any logs.



Got any log4j2 Question?