1

As other posts show (e.g. this here) it's possible to add an appender via code instead of defining it in logback.xml

Problem: the program, as usual, uses a lot different Logger instances in several java classes. All of them instanciated like:

static final Logger logger = (Logger) LoggerFactory.getLogger(SomeClassName.class);

If I now add a new appender canonically (is it canonically?) like....

Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
LoggerContext lc = rootLogger.getLoggerContext();

PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("%date{ISO8601} %level ${PID} %-32c{32} [%12t]: %message%n");
ple.setContext(lc);
ple.start();

SizeAndTimeBasedRollingPolicy<ILoggingEvent> rp = new SizeAndTimeBasedRollingPolicy<>();
rp.setContext(lc);
rp.setMaxHistory(25);
rp.setMaxFileSize(FileSize.valueOf("200KB"));
rp.setTotalSizeCap(FileSize.valueOf("1GB"));
rp.setFileNamePattern(
    "logs/archived/" + Zeb2JiraRESTLoader.class.getSimpleName() + ".%d{yyyy-MM-dd}.%i.log.zip");

RollingFileAppender<ILoggingEvent> rfa = new RollingFileAppender<>();
rfa.setFile("logs/" + Zeb2JiraRESTLoader.class.getSimpleName() + ".log");
rfa.setName("FILE_APPENDER");
rfa.setContext(lc);
rfa.setEncoder(ple);
rfa.setRollingPolicy(rp);

rp.setParent(rfa);
rp.start();
rfa.start();

rootLogger.addAppender(rfa);
rootLogger.setLevel(Level.INFO);
rootLogger.setAdditive(true);

rootLogger.iteratorForAppenders().forEachRemaining(System.out::println);
// leads to console output:
// ch.qos.logback.core.ConsoleAppender[STDOUT] <-- defined in logback.xml
// ch.qos.logback.core.rolling.RollingFileAppender[FILE_APPENDER]

// logger is the logger of this class
logger.iteratorForAppenders().forEachRemaining(System.out::println);
// leads to NO console output at all. List is empty

...the unwanted behaviour is:

  • All Logger instances log into the Appender[STDOUT] defined in the logback.xml file
  • Only logs from the very class, where the new Appender has been added (see code above), log into the newly defined appender.

Wanted behaviour: All Logger instances shall log into both Appenders, the first one defined in the logback.xml file and the second one, defined by the java code above.

Cœur
  • 37,241
  • 25
  • 195
  • 267
karldegen
  • 113
  • 8
  • Did you try the options in this? https://stackoverflow.com/questions/21885787/setting-logback-xml-path-programmatically – aksappy Nov 13 '19 at 18:28
  • @aksappy That post does not address my problem. The program finds the logback.xml file perfectly. – karldegen Nov 13 '19 at 20:59

0 Answers0