简体   繁体   中英

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.

How to configure my application to detect these log files?

log4j must be properly configured for logging to files.

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.

Or you can create multiple logger instances each with one fileAppender if switching is required dynamically throughout the program.

This way of using log4j avoids the need for external configuration file log4j.properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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