Stop log messages from appearing in the command li

2019-08-04 03:50发布

问题:

I have a maven project with the following dependencies for logging:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
</dependency>

My properties file looks like this :

### Default logger configuration ###
log4j.rootLogger = INFO, fa
log4j.appender.fa = org.apache.log4j.FileAppender
log4j.appender.fa.File = logs/ServerLogs.log
log4j.appender.fa.layout = org.apache.log4j.PatternLayout
log4j.appender.fa.layout.ConversionPattern = %d{ISO8601} %p [%t] %c (%F:%L) - %m%n

### Set Settings for Hibernate Logging ###
log4j.logger.org.hibernate = ERROR
### Set Settings for Spring Framework Logging ###
log4j.logger.org.springframework= ERROR

The problem is that when I execute a statement like the following :

logger.info("Initializing DB connection for the first time");

This log message is written in the file that I specified in the properties file but it is also appended in the command line. How can I disable this behavior ? I want the message to printed only in the file , not in the command line .

Any ideas ?

回答1:

I found out that this disables the log4j completely:

org.apache.log4j.LogManager.resetConfiguration();
org.apache.log4j.LogManager.getRootLogger().addAppender(new NullAppender());

If you still want the logging but directed to a file you can do this:

LogManager.resetConfiguration();
LogManager.getRootLogger().addAppender(new FileAppender(new PatternLayout(), "log.log"));