如果您正在阅读此文,您必须使用log4j框架,并收到以下错误消息。
1log4j:WARN No appenders could be found for logger
2log4j:WARN Please initialize the log4j system properly.
3log4j:WARN See https://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Log4j 警告没有附件将用于独立应用程序的控制台和运行在某些服务器容器(如 Tomcat 或 JBoss)中的 Web 应用程序的服务器日志中。
log4j.xml 或 log4j.properties 文件不在 classpath
This is the most common reason, log4j framework look for log4j.xml or log4j.properties file in the classpath of your application. If you have a maven based application, you can create a source folder and put the configuration files there, as shown in below image. If you are using log4j in web applications then check for this configuration file at WEB-INF/classes directory. If it's not there then check that your source folders are properly configured.
- log4j配置文件名称是不同的
Log4j 寻找标准的文件名,所以如果您的 log4j 配置文件名是 myapp-log4j.xml 或 myapp-log4j.properties,那么 log4j 将无法自动加载,您将收到标准的警告消息。
1/**
2 * method to init log4j configurations, should be called first before using logging
3 */
4private static void init() {
5 DOMConfigurator.configure("myapp-log4j.xml");
6 // OR for property file, should use any one of these
7 //PropertyConfigurator.configure("myapp-log4j.properties");
8}
但是你不能使用这个简单的方法与Web应用程序,因为配置文件是在WEB -INF/类目录中。
1public final class Log4jInitListener implements ServletContextListener {
2
3 public void contextDestroyed(ServletContextEvent paramServletContextEvent) {
4 }
5
6 public void contextInitialized(ServletContextEvent servletContext) {
7 String webAppPath = servletContext.getServletContext().getRealPath("/");
8 String log4jFilePath = webAppPath + "WEB-INF/classes/myapp-log4j.xml";
9 DOMConfigurator.configure(log4jFilePath);
10 System.out.println("initialized log4j configuration from file:"+log4jFilePath);
11 }
12
13}
另一种方法是通过下面的 java 选项设置 log4j.configuration系统属性。
1-Dlog4j.configuration=file:///path/to/your/myapp-log4j.xml
Log4j 框架足够聪明,可以基于文件扩展使用 DOMConfigurator 或 PropertyConfigurator. 仅此而已,log4j 就简单易于使用,一旦您掌握了这些初始问题。