2

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?

xav
  • 5,452
  • 7
  • 48
  • 57
devvapp
  • 143
  • 1
  • 2
  • 9
  • possible duplicate of [How to initialize log4j properly?](http://stackoverflow.com/questions/1140358/how-to-initialize-log4j-properly) – kenorb Apr 09 '15 at 19:29

1 Answers1

1

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.

Nikhil Mathew
  • 687
  • 7
  • 17
  • Or you could also write a [configuration file](https://logging.apache.org/log4j/1.2/manual.html) and point it using the startup option `-Dlog4j.configuration=file:log4j.properties` – xav Mar 28 '14 at 17:47
  • Does log4j 2 still use a properties file? I can't find any mention of that in the [log4j web site](http://logging.apache.org/log4j/2.x/manual/configuration.html) – will Aug 19 '14 at 02:49