Is it possible to reload log4j.xml / log4j.propert

2019-02-02 02:56发布

The problem is, whenever you change the log4j.properties/log4j.xml, you need to restart the tomcat [ or say any other server ]. Is there any workaround of reloading the log4j configuration?

8条回答
Summer. ? 凉城
2楼-- · 2019-02-02 03:44

The Guido Garcia answer is quite on target.

Log4j 1 offers a way of reloading log4j configuration in a non JEE thread safe maner.

So if you are in a JEE continer, you can solve your problem trivially by:

(A) Create your @Singleton ejb timer to periodically scan your log4j.properties file

(b) Look at the implementaiton of the log4j log watch given by log4j. What it does when it is time to relaoad a file is quite simply and conveniently, the following:

new PropertyConfigurator().doConfigure(filename,LogManager.getLoggerRepository());

Just do the same, if the time stamp on you configuration file changes. That is it.

查看更多
放我归山
3楼-- · 2019-02-02 03:45

Update:If you are using lg4j2.xml, the configuration is the only thing you will need for log4j to be managed at runtime

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO" monitorInterval="30">
  <Loggers>
-------
  </Loggers>
</Configuration>

Monitor interval 30 loads the log4j changes every 30 seconds.

Below solution is if you are on older version of log4j.

Yes you can change the log4j level at run time without the need to restart the server provided you are using spring.

public class OptionalLog4jConfigurer extends Log4jConfigurer implements
 InitializingBean {

public static final Long DEFAULT_REFRESH = 30000L;
 private static final Log LOG = LogFactory
 .getLog(OptionalLog4jConfigurer.class);

private String configLocation;
 private Long refreshInterval;

public OptionalLog4jConfigurer(final String configLocation,
 final Long refreshInterval) {
 this.configLocation = configLocation;

if (refreshInterval == null) {
 this.refreshInterval = DEFAULT_REFRESH;
 }
 else {
 this.refreshInterval = refreshInterval;
 }
 }


 public void afterPropertiesSet() throws Exception {
 if (!StringUtils.isEmpty(this.configLocation)) {
 LOG.info("Log4J configuration is being customized.");

this.initLoggingInternal();
 }
 else {
 LOG
 .info("Using default Log4J configuration. No customization requested");
 }
 }

public String getConfigLocation() {
 return this.configLocation;
 }

public Long getRefreshInterval() {
 return this.refreshInterval;
 }

}

Then do these changes to applicationContext.

<bean id="optionalLog4jInitialization"  class="com.skg.jetm.OptionalLog4jConfigurer">
<constructor-arg index="0" type="java.lang.String"  value="${log4j.configuration}" />
<constructor-arg index="1" type="java.lang.Long" value="100" />
 </bean>

Full code and explanation can be found here

Changing log4j Level dynamically

查看更多
登录 后发表回答