Learn to configure Log4j2 using Maven and Gradle dependencies.
1. Log4j Modules
The main modules of interest are given below.
- log4j-api – provides the adapter components required for implementers to create a logging implementation.
- log4j-core – core Log4j Implementation classes.
- log4j-slf4j-imp – allows applications coded to the SLF4J API to use Log4j2 as the implementation.
- log4j-jcl – provides a bridge for Apache commons-logging.
- log4j-jul – adapter for Java utility logging (JUL).
- log4j-web – provides support for automatically enabling Log4j in Servlet containers.
We can read the complete list of modules and their dependencies at this link.
2. Maven Dependencies
An example of log4j2 configuration with SLF4J using Maven. We can check the latest version of log4j2 in its Maven dependency page.
<properties>
<log4j2.version>2.20.0</log4j2.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j2.version}</version>
</dependency>
</dependencies>
3. Gradle Dependencies
An example of log4j2 configuration using Gradle.
dependencies {
implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.20.0'
implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.20.0'
implementation group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.20.0'
}
4. Bootstrapping Logger
We can use the LogManager API to bootstrap a Logger instance as follows:
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
public static void main(final String... args)
{
logger.info("Hello Logging!");
}
}
If we are using Log4j2 with SLF4j then we can use the LoggerFactory api.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(final String[] args)
{
logger.info("Hello Logging!");
}
}
Let me know your thoughts in comments or feedback.
Happy Learning !!