How do I set log4j level on the command line?

后端 未结 7 932
暖寄归人
暖寄归人 2020-12-24 10:27

I want to add some log.debug statements to a class I\'m working on, and I\'d like to see that in output when running the test. I\'d like to override the log4j properties on

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-24 10:36

    Based on Thorbjørn Ravn Andersens suggestion I wrote some code that makes this work

    Add the following early in the main method and it is now possible to set the log level from the comand line. This have been tested in a project of mine but I'm new to log4j and might have made some mistake. If so please correct me.

        Logger.getRootLogger().setLevel(Level.WARN);
        HashMap logLevels=new HashMap();
        logLevels.put("ALL",Level.ALL);
        logLevels.put("TRACE",Level.TRACE);
        logLevels.put("DEBUG",Level.DEBUG);
        logLevels.put("INFO",Level.INFO);
        logLevels.put("WARN",Level.WARN);
        logLevels.put("ERROR",Level.ERROR);
        logLevels.put("FATAL",Level.FATAL);
        logLevels.put("OFF",Level.OFF);
        for(String name:System.getProperties().stringPropertyNames()){
            String logger="log4j.logger.";
            if(name.startsWith(logger)){
                String loggerName=name.substring(logger.length());
                String loggerValue=System.getProperty(name);
                if(logLevels.containsKey(loggerValue))
                    Logger.getLogger(loggerName).setLevel(logLevels.get(loggerValue));
                else
                    Logger.getRootLogger().warn("unknown log4j logg level on comand line: "+loggerValue);
            }
        }
    

提交回复
热议问题