Reputation: 1348
I want to use 2 different loggers in a class where one logger uses one logback configuration file and another uses another configuration file. eg:
class Sample {
// LOGGER 1 follows configuration from logback1.xml
private static final LOGGER1 = LoggerFactory.getLogger(Sample.class);
// LOGGER 2 follows configuration from logback2.xml
private static final LOGGER2 = LoggerFactory.getLogger(Sample.class);
public myFunc(){
LOGGER1.info("In myFunc"); // writes to file as configured in logback1.xml
LOGGER2.info("Entered myFunc"); // writes to graylog server as configured in logback2.xml
}
}
The reason I want to do this is that I'm injecting a second logger into code at runtime, and I don't want the injected logger to collide with the logger used in the main project. How should I go about doing this?
I went through this post: How to use multiple configurations with logback in a single project? But it seems to address the problem of choosing one configuration file from many but not "being able to use 2 configuration files simultaneously as in the above example."
Upvotes: 3
Views: 1337
Reputation: 136062
This is one way to get two loggers from different configs:
LoggerContext c1 = new LoggerContext();
LoggerContext c2 = new LoggerContext();
new ContextInitializer(c1).configureByResource(new URL("file:logback1.xml"));
new ContextInitializer(c2).configureByResource(new URL("file:logback2.xml"));
Logger l1 = c1.getLogger("x");
Logger l2 = c2.getLogger("x");
Upvotes: 2