为什么我的log4j消息没有出现在日志文件中?

时间:2019-03-04 22:16:05

标签: java spring log4j

我已经创建了log4j.properties文件并将其放在/src/main/resources/下,该文件的内容为:

log4j.rootLogger = DEBUG, FILE
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=log.out
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite
log4j.appender.FILE.Append=false

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

我想查看文件log.out中的日志,但是当我使用以下命令运行该应用程序时:

java -jar myapp.jar -Dlog4j.debug

未创建文件。

这是-根据注释的要求-我如何在代码中使用它:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

private static final Logger LOG = LogManager.getLogger(MyClass.class);

及更高版本:

LOG.debug("some message");

LOG.error("some other msg", error);

1 个答案:

答案 0 :(得分:1)

请在下面找到实现

  

log4j.properties

  

src / main / resources

`

# Root logger option
log4j.rootLogger=INFO, stdout, file

# Redirect log messages to 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

# Redirect log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
#outputs to Tomcat home
log4j.appender.file.File=D:/demo/logs/myapp/myapp.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

与此同时,我还在Logger中导入了class

package org.nbk.demo;
import org.apache.log4j.Logger;
public class ServerStartup {
    private static final Logger logger = Logger.getLogger(ServerStartup.class);
    public void onApplicationEvent() {
            logger.info("Information Messages");
    }
}