Programmatically configure LogBack appender

前端 未结 5 688
死守一世寂寞
死守一世寂寞 2020-11-28 23:50

I have a logback appender defined in the logback.xml, it\'s a DB appender, but I\'m curious if there is any way to configure the appender in java using my own connection poo

5条回答
  •  暖寄归人
    2020-11-29 00:36

    Not allowed to comment (yet?), I'd just like to add three tips;

    • regarding the caveats above, if you have problems, just add a call to

      StatusPrinter.print(context);
      

      after everything has been configured, that is, after having added your appenders the root/"Main" appender: it will tell you what is wrong.

    • I like very much to separate logging-levels in different files; when looking for errors I begin with looking in the error file and so on, having them set up like

    tot_[app name].log   : Level.INFO
    deb_[app name].log   : Level.DEBUG
    err_[app name].log   : Level.ERROR
    

    routing by means of a simple private filter class such as

        private static class ThresholdLoggerFilter extends Filter {
    
            private final Level level;
    
            private ThresholdLoggerFilter(Level level){
                this.level = level;
            }
    
            @Override
            public FilterReply decide(ILoggingEvent event) {
                if (event.getLevel().isGreaterOrEqual(level)) {
                    return FilterReply.NEUTRAL;
                } else {
                    return FilterReply.DENY;
                }
            }
        }
    

    and then just call myFilter.start() and myAppender.addFilter(myFilter);.

    • Lastly, putting it together, I usually want to be able to change log levels dynamically having the setup implement some simple interface like

      public interface LoggingService {
          void setRootLogLevel(Level level);
      }
      

    keeping the root logging level in some property-file which is monitored so that whenever there is some valid input there, I just call this service implemented like

        @Override
        public void setRootLogLevel(Level level) {
            if (context != null && context.isStarted()) {
            ((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(level);
            }
        }
    

    with my new root logger level.

提交回复
热议问题