Getting properties programmatically from Log4j2 XML config

Viewed 5157

In my Log4j2 config file, I have this:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" strict="true" name="XMLConfig" packages="org.apache.logging.log4j.test">
    <Properties>
        <Property name="baseDir">log-dir/</Property>
        <Property name="defaultLogfileName">default-log-file</Property>
    </Properties>

Now, in some of my code, I create custom loggers. I need to access the value of "baseDir" and change it. I've tried using getProperties from the context like this:

LoggerContext context = (LoggerContext) LogManager.getContext(false);
Configuration configuration = context.getConfiguration();
configuration.getProperties();

But the map that comes back has the keys "hostname" and "contextName". Not the properties map that I was looking for.

I thought that I might be able to get it from the rootLogger:

LoggerContext context = (LoggerContext) LogManager.getContext(false);
Configuration configuration = context.getConfiguration()
for (Property p : configuration.getRootLogger().getPropertyList())
{
    ...
}

But this yields a NullPointerException because getPropertyList returns null.

So, how can I access the property with the name "baseDir" so that I can programmatically create a new logger, but with a different base directory?

1 Answers
Related