How to change log4j setting during application run

2019-04-05 04:42发布

问题:

Is it possible to change log4j settings during application execution?

回答1:

You can use PropertyConfigurator.configureAndWatch to make log4j spawn a thread to periodically check your properties file for changes.

Alternatively, you can use JMX described in this post: Change Logging Levels using JMX



回答2:

There ways of doing this by making your Log4j accessible through JMX and using a JMX console to control the filters, loggers, levels, appenders etc...

I have an example somewhere but I need to prune it a little to make it understandable. Would you want this ?



回答3:

I'm using:

  • Windows 7
  • Apache Tomcat 7.0.34
  • log4j 1.2.17

and it is done automatically (no need to restart Tomcat) if you follow the next steps (let's suppose that you have already deployed the war file to %CATALINA_HOME%\webapps and you have launched startup.bat):

  1. Go to %CATALINA_HOME%\webapps\YourApp\WEB-INF\classes
  2. Edit log4j.properties / log4j.xml and change the logger level

    E.g.:

    • log4j.properties:

      log4j.rootLogger=INFO, stdout, file
      

      becomes

      log4j.rootLogger=DEBUG, stdout, file
      
    • log4j.xml

      <root>
          <level value="INFO" />
          <appender-ref ref="console" />
          <appender-ref ref="file" />
      </root>
      

      becomes

      <root>
          <level value="DEBUG" />
          <appender-ref ref="console" />
          <appender-ref ref="file" />
      </root>
      

    If you have both files in the classes folder, the XML file will be considered (the .properties file will be ignored).

  3. In 0-10 seconds you'll be able to see the following lines in Tomcat console and in %CATALINA_HOME%\logs\catalina.yourDate.log:

    Nov 12, 2015 4:52:49 PM org.apache.catalina.core.StandardContext reload

    INFO: Reloading Context with name [/YourApp] has started

    Nov 12, 2015 4:52:50 PM org.apache.catalina.loader.WebappClassLoader validateJarFile

    INFO ...

    Nov 12, 2015 4:52:50 PM org.apache.catalina.core.StandardContext reload

    INFO: Reloading Context with name [/YourApp] is completed

  4. Use the application and see the new logging level (in console and/or in the logging files).



标签: java log4j