简体   繁体   English

Log4j配置问题-log4j:WARN请正确初始化log4j系统

[英]Log4j Configuration issues - log4j:WARN Please initialize the log4j system properly

I got error: 我收到错误消息:

log4j:WARN No appenders could be found for logger (java.lang.Class).
log4j:WARN Please initialize the log4j system properly.

I have been through many threads and forums to fix the above error, but could not find the solution to my problem. 我已经通过许多线程和论坛来解决上述错误,但是找不到解决我问题的方法。

Problem: My requirement specifies us to use the below filenames for each environment. 问题:我的要求指定我们在每种环境下使用以下文件名。

log.dev log.dev
log.local log.local
log.test log.test

How to configure my application to detect these log files? 如何配置我的应用程序以检测这些日志文件?

log4j must be properly configured for logging to files. 必须正确配置log4j才能记录到文件。

try this : 尝试这个 :

Logger logger = Logger.getLogger(yourclassname.class);
BasicConfigurator.configure(); // basic log4j configuration
Logger.getRootLogger().setLevel(Level.INFO);  
FileAppender fileAppender = null;
try {
  fileAppender =
      new RollingFileAppender(new PatternLayout("%d{dd-MM-yyyy HH:mm:ss} %C %L %-5p:%m%n"),"file.log"); 
  logger.addAppender(fileAppender);  
} catch (IOException e) {
  e.printStackTrace();
}

logger.info("TEST LOG ENTRY");

This should create a log file named file.log in the local folder. 这应该在本地文件夹中创建一个名为file.log的日志文件。 Use your java program and logic to removeAppender and addAppender as necessary to switch files. 根据需要使用Java程序和逻辑来删除removeAppender和addAppender来切换文件。

Or you can create multiple logger instances each with one fileAppender if switching is required dynamically throughout the program. 或者,如果需要在整个程序中动态切换,则可以创建多个记录程序实例,每个记录程序实例带有一个fileAppender。

This way of using log4j avoids the need for external configuration file log4j.properties. 这种使用log4j的方式避免了对外部配置文件log4j.properties的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM