Change log4j properties at runtime

2019-01-14 12:46发布

I need to change my log4j properties (rootLogger, MaxFileSize, etc.) at runtime. How can I do this?

标签: log4j
2条回答
闹够了就滚
2楼-- · 2019-01-14 13:23

Use LogManager.resetConfiguration(); to clear the current config and configure it again.

Another approach is to build a new appender and replace the old one with it (most appenders don't support changing their config). This way, all the loggers (and their levels, etc) stay intact.

For this to work, I usually add the first appender from code (and not with a config file). That allows me to save a reference which makes it more simple to remove it later.

查看更多
3楼-- · 2019-01-14 13:23

https://github.com/apache/jena/blob/master/jena-tdb/log4j.properties has a log4j properties file.

Based on it I am using the configureLog4j helper function shown below like this:

set jena logging level at runtime

String level=org.apache.log4j.Level.OFF.toString();
if (debug)
  level=org.apache.log4j.Level.INFO.toString();
configureLog4j(level);

configureLog4J function

  /**
   * configure Log4J
   * @param level -the level to use e.g. "INFO", "DEBUG", "OFF" 
   * see org.apache.log4j.Level
   */
  private void configureLog4j(String level) {
    Properties props = new Properties();
    props.put("log4j.rootLogger", level+", stdlog");
    props.put("log4j.appender.stdlog", "org.apache.log4j.ConsoleAppender");
    props.put("log4j.appender.stdlog.target", "System.out");
    props.put("log4j.appender.stdlog.layout", "org.apache.log4j.PatternLayout");
    props.put("log4j.appender.stdlog.layout.ConversionPattern",
        "%d{HH:mm:ss} %-5p %-25c{1} :: %m%n");
    // Execution logging
    props.put("log4j.logger.com.hp.hpl.jena.arq.info", level);
    props.put("log4j.logger.com.hp.hpl.jena.arq.exec", level);
    // TDB loader
    props.put("log4j.logger.org.apache.jena.tdb.loader", level);
    // Everything else in Jena
    props.put("log4j.logger.com.hp.hpl.jena", level);
    props.put("log4j.logger.org.apache.jena.riot", level);
    // TDB
    // TDB syslog.
    props.put("log4j.logger.TDB", level);
    props.put("log4j.logger.com.hp.hpl.jena.tdb", level);
    props.put("log4j.logger.com.hp.hpl.jena.tdb.transaction", level);
    props.put("log4j.logger.com.hp.hpl.jena.tdb.transaction.NodeTableTrans",
        level);
    props.put("log4j.logger.com.hp.hpl.jena.tdb.transaction.TransactionManager",level);
    props.put("log4j.logger.com.hp.hpl.jena.tdb.transaction.TestTransSystem",level);
    // Joseki server
    props.put("log4j.logger.org.joseki", level);
    LogManager.resetConfiguration();
    PropertyConfigurator.configure(props);
  }
查看更多
登录 后发表回答