Log4j 报错 No appenders could be found for logger

在使用 Log4j 打印日志时出现如下报错:

1
2
3
log4j:WARN No appenders could be found for logger (com.zhangzw.search.BinarySearch).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

查看官网说明:

Why do I see a warning about “No appenders found for logger” and “Please configure log4j properly”?

This occurs when the default configuration files log4j.properties and log4j.xml can not be found and the application performs no explicit configuration. log4j uses Thread.getContextClassLoader().getResource() to locate the default configuration files and does not directly check the file system. Knowing the appropriate location to place log4j.properties or log4j.xml requires understanding the search strategy of the class loader in use. log4j does not provide a default configuration since output to the console or to the file system may be prohibited in some environments. Also see FAQ: Why can’t log4j find my properties in a J2EE or WAR application?

意思就是没有找到默认的 Log4j 配置文件 log4j.properties 或 log4j.xml,所以我们创建个 log4j.properties 文件放到 resources 目录下就可以了。

附 log4j.properties 的简单配置:

1
2
3
4
log4j.rootCategory=info, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss SSS}] [%-5p] %C{1}.%M(%L) - %m%n