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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22687672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:17:13  来源:igfitidea点击:

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

javalogginglog4jenvironment

提问by devvapp

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.local
log.test

log.dev
log.local
log.test

How to configure my application to detect these log files?

如何配置我的应用程序以检测这些日志文件?

回答by Nikhil Mathew

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. Use your java program and logic to removeAppender and addAppender as necessary to switch files.

这应该在本地文件夹中创建一个名为 file.log 的日志文件。根据需要使用您的 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 的需要。