log4j 1.x to log4j 2.x migration
What's inside this article
⌄
- How to migrate from log4j 1.x to log4j 2.x
- How to make log4j bridge migration
- How to use log4j 2.x if log4j 1.x classes still required
- How to use log4j bridge with slf4j
- Log4j-1.2-api and slf4j
Even though you may want to merely copy and paste the code below, I suggest you firstly explore carefully the article describing how Java logging works, what is slf4j, what is log4j, what is bridge and how it works: How Java logging should work, and then get back to here.
Suppose you have these two at-a-glance controversial requirements:
- You need to use log4j 2.x because of security department
- You have dependencies with log4j 1.x support only
To satisfy these needs, we’re doing the following things:
- locking slf4j version (
slf4j-api) - importing log4j 2.x jars (
log4j-api;log4j-core) - connecting log4j 2.x to slf4j (
log4j-slf4j-impl) - providing log4j 1.x api support without using log4j 1.x (
log4j-1.2-api)
So you need to ensure that you don’t have any transitive log4j dependencies from other libraries, then add this bunch of dependencies to your pom.xml:
<log4j2.version>2.17.2</log4j2.version>
<slf4j.version>1.7.30</slf4j.version>
<!-- Lock slf4j facade version -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log4j 2.x-->
<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>
<!-- log4j 2.x to slf4j binding -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!-- Compatibility of log4j 1.x related code -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-1.2-api</artifactId>
<version>${log4j2.version}</version>
</dependency>