修复log4j WARN找不到记录器的附加程序,请正确初始化log4j系统

时间:2020-02-23 14:37:19  来源:igfitidea点击:

如果您正在阅读本文,则必须使用log4j框架并收到以下错误消息。

log4j:WARN No appenders could be found for logger
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See https://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

对于独立应用程序,控制台将出现Log4j警告,没有附加程序将出现在控制台中;对于运行到某些servlet容器(例如Tomcat或者JBoss)中的Web应用程序,将在服务器日志中显示警告。

log4j可能有多种原因警告未找到任何附加程序,让我们看看常见原因以及如何解决它们。

  • log4j.xml或者log4j.properties文件不在类路径中

这是最常见的原因,log4j框架在应用程序的类路径中查找log4j.xml或者log4j.properties文件。
如果您具有基于Maven的应用程序,则可以创建一个源文件夹并将配置文件放其中,如下图所示。

如果在Web应用程序中使用log4j,则在WEB-INF/classes目录中检查此配置文件。
如果不存在,请检查您的源文件夹是否已正确配置。

  • log4j配置文件名有所不同

Log4j查找标准文件名,因此,如果您的log4j配置文件名是myapp-log4j.xml或者myapp-log4j.properties,则log4j将无法自动加载它,并且您会收到标准警告消息。

对于独立的Java应用程序,可以在使用它之前通过在main方法内对其进行配置来轻松修复它。
例如;

/**
 * method to init log4j configurations, should be called first before using logging
 */
private static void init() {
	DOMConfigurator.configure("myapp-log4j.xml");
	//OR for property file, should use any one of these
	//PropertyConfigurator.configure("myapp-log4j.properties");
}

但是您不能在Web应用程序中使用这种简单的方法,因为配置文件位于WEB-INF/classes目录中。
您可以通过ServletContextListener进行此配置,如下面的代码所示。

public final class Log4jInitListener implements ServletContextListener {
 
  public void contextDestroyed(ServletContextEvent paramServletContextEvent)  { 
  }
 
  public void contextInitialized(ServletContextEvent servletContext)  { 
      String webAppPath = servletContext.getServletContext().getRealPath("/");
  String log4jFilePath = webAppPath + "WEB-INF/classes/myapp-log4j.xml";
      DOMConfigurator.configure(log4jFilePath);
      System.out.println("initialized log4j configuration from file:"+log4jFilePath);
  }
   
}

另一种方法是通过如下所示的java选项设置log4j.configuration系统属性。

-Dlog4j.configuration=file:///path/to/your/myapp-log4j.xml

Log4j框架足够聪明,可以根据文件扩展名使用DOMConfigurator或者PropertyConfigurator。