Search code examples
javamavenlog4jlog4j2maven-dependency

LoggerContext import fails for log4j 2.17.1 in spite of adding Maven dependency


I am trying to use LoggerContext in my Java code.

Added the Maven dependency in pom.xml:

<dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.1</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </exclusion>
        </exclusions>
</dependency>
<dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.17.1</version>
</dependency>

The piece of code that I am trying to add:

import org.apache.logging.log4j.core.LoggerContext;
LoggerContext context = (LoggerContext) LogManager.getContext(false);
File file = new File("path/to/a/different/log4j2.xml");

However, my import statement errors out. I am using IntelliJ IDE and the 'Add Maven Dependency' option in the IDE that searches for the class also doesn't return any results for org.apache.logging.log4j.core.LoggerContext

I tried re-building the project from the IDE, but, that didn't help.

What am I missing?


Solution

  • The code looks good to my eyes, most likely IntelliJ hasn't pulled in the dependency.

    To diagnose:

    • run build via mvn install on command line. Inspect the output. If the build passes, this will limit the problem to IntelliJ
    • use Reload All Maven Projects on Maven tab in IntelliJ