My old Log4j 1.x code looks like this:
PropertyConfigurator.configure(getClass().getResourceAsStream("/log4j.properties"));
I am trying to find the equivalent of Log4j 2.x, but so far I have not been successful. I started digging through my code, I know that context.setConfigLocation(f.toURI()) works well, and I found a private setConfiguration() method in LoggerContext that can do the trick, so I hack it for the public and end up method:
public static String configLog4j2(InputStream in) { if (in == null) { String msg = "Error, InputStream is null"; System.err.println(msg); return msg; } try { LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false); ConfigurationSource source = new ConfigurationSource(in); Configuration instance = ConfigurationFactory.getInstance().getConfiguration(context, source); Class[] args = new Class[1]; args[0] = Configuration.class; Method method = context.getClass().getDeclaredMethod("setConfiguration", args); method.setAccessible(true); method.invoke(context, instance); } catch (Exception exr) { String msg = "Error, config log4j2 by inputStream failed, " + exr.getMessage(); System.err.println(msg); return msg; } return "ok"; }
It seems to work well, however this is a private method, possibly changed in state in a future version.
Is there an official Log4j 2 API that can do this?
java log4j2
Wei kleeff
source share