devvapp
devvapp

Reputation: 143

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

How to configure my application to detect these log files?

Upvotes: 2

Views: 15866

Answers (1)

Nikhil Mathew
Nikhil Mathew

Reputation: 687

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.

Upvotes: 1

Related Questions