I'm working with a third-party log4j v2 Appender which gives me the opportunity to plug-in some custom classes of my own (the Appender will create those via Reflection).
In other words: My class gets instantiated from the Appender which again gets instantiated as part of log4j's normal bootstrap. I do not have control over the Appender which is from another library.
I would like a few properties for my own custom class to be read from the Log4j configuration. It makes sense that it lives there since it is indeed related to logging.
However, I cannot figure out how to do this. At the moment I do something like this from the constructor of my custom class:
LoggerContext loggerContext = LoggerContext.getContext(true);
if (loggerContext != null) {
Configuration config = loggerContext.getConfiguration();
if (config != null) {
StrSubstitutor strSubstitutor = config.getStrSubstitutor();
if (strSubstitutor != null) {
StrLookup variableResolver = strSubstitutor.getVariableResolver();
if (variableResolver != null) {
String myVar = variableResolver.lookup("myPropertyName");
}
}
}
}
but the problem seems to be that at this point in time (during bootstrap) the Log4j configuration is indeed not yet initialized so
LoggerContext.getContext(true).getConfiguration()
returns an instance of DefaultConfiguration
(which obviously doesn't have my property) where
I would have expected an instance of XmlConfiguration
. The latter I get when I call LoggerContext.getContext(true).getConfiguration()
at any later point in time and I can indeed read my custom properties from that one.