0
votes

I put a dependency of log4j in pom.xml file:

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

wrote the following log4j.properties file:

log4j.rootLogger=INFO, stdout, console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

and put this file under 'resources' folder.

Lastly, I put environment variable LOG4J_log4j.configurationFile = log4j.properties

Still, when I run my application, the line:

logger.info("Hello");

does not write anything to console. Do you know what can be the problem?

2

2 Answers

4
votes

You are using log4j2, your properties file name should be log4j2.properties. And you can configure it like below. You don't have to put any enviromental variable.

appenders = console
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 

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

source = https://springframework.guru/log4j-2-configuration-using-properties-file/

1
votes

I suggest that you start with a working example first, then add the specifics of your own configuration step by step. Then you see where it breaks.

In your above code I see the following potential issues:

  • In line "log4j.rootLogger=INFO, stdout, console" you're referring to an appender named "console" that isn't defined. This might throw an exception internally that gets never logged anywhere because the logging itself isn't working because of that.
  • Your approach of configuring the configuration file location by an environment variable doesn't seem to be documented anywhere. Where do you have this from. If the file is in the resources directory, as you say, it will end up at the root of the classpath. If that's so, it can be pointed to as described here: Where is the correct location to put Log4j.properties in an Eclipse project?, that is by adding the command line switch -Dlog4j.configuration=file:log4j.properties when starting the JVM.
  • There may be a conflict in the format of the log4j.properties file and the version of log4j you're using. The properties file seems to belong to log4j whereas your Maven artifact refers to log4j2.