Issue
while migrating a project from log4j to log4j2 I encountered a situation when a logger that logs events to a separate file (let's call it uu.log
) has to be added at runtime - all other loggers are configured in properties file. The below code is almost doing the job - namely, uu.log
contains events from all existing loggers, not just from new one. This is what I try so far: How can I fix the code below to achieve the desired state in simplest way?
public class MultipleLoggersExample {
public static void main(String[] args) throws InterruptedException {
// this logger is configured in properties file and is logging to own file
Logger aud = LogManager.getLogger("aud");
// class B is logging to separate file (logger also defined in properties)
B b = new B();
// below classes should log to common file NormalLog.log defined in properties
C c = new C();
D d = new D();
E e = new E();
addLoggerAtRuntime();
// this logger needs to log only its OWN messages to uu.log file
Logger runtimeLogger = LogManager.getLogger("my runtime logger");
int counter = 2;
while(true) {
if(counter % 2 == 0){
aud.info("message from \"aud\" logger no. "+ (counter-1));
} else{
b.logger.info("message from class B no. " + (counter-1));
}
c.logger.info("message from class C");
e.logger.info("message from class E");
if(counter % 4 == 0) {
runtimeLogger.info("message from logger added at runtime");
}
counter++;
Thread.sleep(5_000);
}
}
private static void addLoggerAtRuntime() {
final String fileName = "C:\\Users\\Damian\\Desktop\\uu.log";
LoggerContext lc = (LoggerContext) LogManager.getContext(false);
RollingFileAppender rfa = RollingFileAppender.newBuilder()
.withName("my runtime logger").withAppend(true)
.withFileName(fileName)
.withLayout(PatternLayout.newBuilder().withPattern("%-5p %d [%t] %C{2} - %m%n").build())
.withPolicy(TimeBasedTriggeringPolicy.newBuilder().withModulate(true).withInterval(2).build())
.withFilePattern(fileName + "." + "%d{yyyy-MM-dd-HH-mm}")
.setConfiguration(lc.getConfiguration()).build();
rfa.start();
lc.getConfiguration().addAppender(rfa);
lc.getRootLogger().addAppender(lc.getConfiguration().getAppender(rfa.getName()));
lc.updateLoggers();
}
}
Solution
Appender names have no relationship to logger names, so this:
.withName("my runtime logger")
is pointless. You might as well use "My appender"
or something.
The problem is this:
lc.getRootLogger().addAppender(
You’re adding your Appender to the root logger, from which all other loggers inherit, so of course all loggers are using it. Try adding the Appender to just your logger:
lc.getLogger("my runtime logger").addAppender(
Answered By - VGR
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.