Fell Fell - 1 year ago 139
Java Question

configure log4j to log to custom file at runtime

Can anyone please guide me as to how I can configure log4j to log to a specific file that I specify at run-time.The name and path of the log file are generated at run-time and the application must log to that particular file.

Generally file appender entries in the log4j.properties file points to the log file that will be used by the application.However in this case I would like to read the log file path from the command line and log to that particular file.

How can I achieve this ?

Thanks in advance,

Answer Source

Adapted from the log4j documentation:

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.FileAppender;

public class SimpandFile {
   static Logger logger = Logger.getLogger(SimpandFile.class);
   public static void main(String args[]) {

      // setting up a FileAppender dynamically...
      SimpleLayout layout = new SimpleLayout();    
      FileAppender appender = new FileAppender(layout,"your filename",false);    

      logger.setLevel((Level) Level.DEBUG);

      logger.debug("Here is some DEBUG");
      logger.info("Here is some INFO");
      logger.warn("Here is some WARN");
      logger.error("Here is some ERROR");
      logger.fatal("Here is some FATAL");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download