Search code examples
javalogginglog4jdefault

log4j 1.x : detect if no config file given and programmatically set it up


(If your using log4j version 2 this is not applicable)

Know how to set log4j to print debug and how to pro grammatically construct a default Properties object.

Want help with code to detect if log4j did not find a config file in classpath.

This for the times when don't have a log4j.xml to at least see all logs in console.

Code I have:

private static void log4Default() {
        boolean noLog = true;
  //how to set this to false if log4j did find a config file
//      File log4f = new File("log4j.xml");
//      File log4f2 = new File("log4j.properties");
//      
//      if(log4f.exists() || log4f2.exists()) {
//          noLog = false;
//      }else {
//          log4f = new File("target/classes/log4j.xml");
//          log4f2 = new File("target/classes/log4j.properties");
//          if(log4f.exists() || log4f2.exists()) {
//              noLog = false;
//          }
//      }
//      if(noLog) {
//          log4f = new File("target/test-classes/log4j.xml");
//          log4f2 = new File("target/test-classes/log4j.properties");
//          if(log4f.exists() || log4f2.exists()) {
//              noLog = false;
//          }
//      }

        if(noLog) {
            System.out.println("no log4j config, using default");
            Layout layout = new PatternLayout(" %-5p %t %d [%t][%F:%L] : %m%n");
            Appender ap = new ConsoleAppender(layout , ConsoleAppender.SYSTEM_OUT);
            Logger.getRootLogger().setLevel(Level.ALL);
            //Logger.getRootLogger().addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_ERR));
            Logger.getRootLogger().addAppender(ap);
        }

    }

Commented out the file exists as there could be an over ride and above is not foul proof.


Solution

  • You can use this to check whether there is any log4j.xml/.properties file present in the classpath:

    public void checkForLog4jConfigFile() {
    
    org.apache.log4j.Logger rootLogger = org.apache.log4j.Logger.getRootLogger();
    Enumeration appenders = rootLogger.getAllAppenders();
    if (!appenders.hasMoreElements()) {
        System.out.println("LOG4J config file is missing");
    } else {
        System.out.println("appender found "
        + ((Appender) appenders.nextElement()).getName());
    }
    }