简体   繁体   中英

log4j2 adding logger + appender by code

I am trying to add by code a custom appender that should log some package. And everything works using this code :

String loggerName = "org.test";
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration cfg = ctx.getConfiguration();
if (cfg instanceof XmlConfiguration) {
       //add appender if not added
       Appender appender = cfg.getAppender(MyAppender.NAME);
if (appender == null) {
            Appender appender = MyAppender.createAppender(MyAppender.NAME, "%highlight{%d [%t] %-5level: %msg%n%throwable}", "false", null);
            appender.start();
            cfg.addAppender(appender); 
}
LoggerConfig logger = ((XmlConfiguration) cfg).getLogger(loggerName);
            if (logger == null) {
                logger = new LoggerConfig(loggerName, Level.DEBUG, true);
                cfg.addLogger(loggerName, logger);
            }
           logger.addAppender(appender, Level.DEBUG, null);
} //closing the instanceof XMLConfiguration part

So in short.. as you can see I am creating an appender if there was no appender defined before. Then I am creating a logger for org.test if there was no added and adding the appender to this logger.

Everything is fine except one thing: The new appender and logger works correctly. However I have other appenders in my XML configuration Console Appender and so on.. and for some reason they are ALSO added as DEBUG level for the org.test logger... even if this logger doesnt have ANY other appenders configured like in my case.. I am debuging .. it has ONLY one appender, in the configuration object.. but the logger still sends debug messages to ALL appends that I have... (I guess all that I have on ROOT level which were set to INFO) ... from now on are also showing DEBUG messages from org.test ... how I can remove this appends and use only this one.. :(

Thanks.

This is happening because the additivity property of the logger is true by default. When this property is true the log messages are propagated to the parent loggers, in your case the ROOT one, I think. Set the additivity property in the logger to false and you will get the desired output. More details here http://logging.apache.org/log4j/2.x/manual/configuration.html#Additivity .

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