25

I have my log4j2.xml config file set to be checked every 30 seconds:

<Configuration status="WARN" monitorInterval="30">
    ...
</Configuration>

Is it possible to programmatically tell log4j2 to check for changes in the configuration instead of having a timeout?

N.B. I don't want to programmatically load the configuration specifying the config file, I just want to tell log4j2 to check the config file that has been loaded before as if the monitorInterval expired.

Thanks!

Remko Popma
  • 35,130
  • 11
  • 92
  • 114
jamp
  • 2,159
  • 1
  • 17
  • 28

4 Answers4

32

It looks like I've found the solution:

((org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false)).reconfigure();

Does anyone see anything wrong/side-effects with this?

jamp
  • 2,159
  • 1
  • 17
  • 28
  • 1
    Unfortunately, I found this problemmatic when there are multiple logging contexts, like in OSGI or in web apps. In this case the code above reloads config in only one of the contexts – plinyar Mar 31 '17 at 13:44
  • 1
    @plinyar what would the solution for OSGI/web-apps environment? – Gaurav Mar 21 '19 at 07:19
  • Sorry, @gaurav, already don't remember. Finally I preferred LogBack – plinyar Mar 22 '19 at 08:51
5

There is currently no clean way to do this. It can be done with reflection. (Of course this may break if the implementation changes.)

UPDATE: this is wrong. There is a clean way, see jamp's answer below.

org.apache.logging.log4j.core.LoggerContext ctx = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);

org.apache.logging.log4j.core.config.FileConfigurationMonitor mon = (org.apache.logging.log4j.core.config.FileConfigurationMonitor) ctx.getConfiguration().getConfigurationMonitor();

// use reflection to get monitor's "nextCheck" field.
// set field accessible
// set field value to zero

mon.checkConfiguration();
Remko Popma
  • 35,130
  • 11
  • 92
  • 114
  • Oh. There is no API for doing what you want to do. I honestly believe reflection is your only option with log4j-2.1. You can of course raise a feature request on the Jira issue tracker. – Remko Popma Jan 30 '15 at 10:45
  • It looks like you're right... can't find anything... :( Much to my regret, I'll accept it ;) – jamp Jan 30 '15 at 11:49
  • I take it back... I might have found a solution... I posted it as an answer – jamp Jan 30 '15 at 12:08
1

What about using org.apache.logging.log4j.core.config.Configurator ?

   LoggerContext loggerContext = LoggerContext.getContext(false);
   final Configuration configuration = loggerContext.getConfiguration();
   Configurator.reconfigure(configuration);
Yoraco Gonzales
  • 727
  • 10
  • 18
0

What about org.apache.logging.log4j.core.config.Configurator.reconfigure()?

Adrian Ber
  • 20,474
  • 12
  • 67
  • 117