简体   繁体   中英

How to change Appender layout programmatically in log4j2?

Previously in log4j 1.x I was able to to appender.setLayout() on and Appender but now in log4j 2.x there is no such method as setLayout(). How can I set a layout to an Appender object programmatically in log4j2 ?

There is no setLayout() method. You will need to get the current Configuration and update it during runtime as explained in the documentation .

You can add you own layout in this way (example with ConsoleAppender):

// rootLoggerConfig you can get from LoggerContext.getRootLogger().get()

String pattern = "%d [%p|%c|%C{1}] %m%n"; // your pattern here

PatternLayout pl = PatternLayout.newBuilder().withPattern(pattern).build();
ConsoleAppender consoleAppender = ConsoleAppender.createDefaultAppenderForLayout(pl);

rootLoggerConfig.addAppender(consoleAppender, Level.getLevel("INFO"), filter);

// filter - your implementation of 
// org.apache.logging.log4j.core.filter.AbstractFilter

If, by chance, you simply want to change the pattern used for different kinds of log events you can use the pattern selector. Otherwise, understanding your use case better might provide other alternatives. In fact, I would love to know why you would want to change the layout programmatically as it is unusual to have a request to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM