Hi all,
i need to configure log4j2 both with XML (that should log on console) and
with some programmatic appenders that creates a log for each time it's
created.
This is the simpe xml configuration:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} -
%msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="error" additivity="false">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
while for creating and removing the appenders and log configs on the fly
i'm using:
public void addAppender(String path, String logFileName) {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
Layout<? extends Serializable> layout = PatternLayout.newBuilder()
.withPattern("%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} -
%msg%n").build();
appenderName = "com" + System.currentTimeMillis();
appender = FileAppender.newBuilder().withName(appenderName)
.withFileName(path + File.separator + logFileName +
".log").withAppend(false).withImmediateFlush(false)
.withLayout(layout).build();
appender.start();
config.addAppender(appender);
AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
AppenderRef[] refs = new AppenderRef[] { ref };
LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.DEBUG,
logFileName, "true", refs, null, config, null);
loggerConfig.addAppender(appender, null, null);
config.addLogger("com", loggerConfig);
ctx.updateLoggers();
}
public void removeAppender() {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
ctx.getLogger("com").removeAppender(appender);
ctx.updateLoggers();
ctx.reconfigure();
}
Now every time i call the addAppender a new appender is created and a new
file is created with the related logs. But i got no logs in the console.
How to solve this ?
Regards,
Pierpaolo
|