Programmatically Enable Logback in Debug Mode?

别来无恙 提交于 2019-12-24 10:14:56

问题


I was wondering if there is a way to enable debug mode programmatically. Since I'm not allowed to use configuration file, I'm currently configure everything programmatically. Recently, I ran into an issue where RollingFileAppender stop writing to file though FileAppender works perfectly fine. In fact, RollingFileAppender was also working last week and nothing that I'm aware of has changed since.

Please let me know if there is a way to enable debug since doing it using configuration file (logback.xml) doesn't seem to be working.


回答1:


Tony has provided an excellent answer here after I posted the question.

http://old.nabble.com/Enable-Debugging-Mode-Programmatically--td32961424.html

This is very helpful when you are trying to figure out why LogBack doesn't work in certain cases. I opted to use the first way for my initialization code.

Keep in mind that this is when you choose not to use a config file like in my kind of use case.


From: tony19

There are a couple ways:

1) Use StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext)

OR

2) Load hard-coded string of configuration XML w/configuration.debug set to 'true':

static final String LOGBACK_XML = 
    "<configuration debug='true'>" + 
    "  <appender name='FILE' class='ch.qos.logback.core.RollingFileAppender'>" +
    "    <file>foo.log</file>" +
    "    <append>true</append>" +
    "    <encoder>" +
    "      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>" +
    "    </encoder>" +
    "  </appender>" +
    "  <root level='INFO'>" +
    "    <appender-ref ref='FILE' />" +
    "  </root>" +
    "</configuration>"
    ;

static public void configLogback() {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
            try {
           JoranConfigurator configurator = new JoranConfigurator();
           configurator.setContext(lc);
           lc.reset();

           configurator.doConfigure(new ByteArrayInputStream(LOGBACK_XML.getBytes()));
       } catch (JoranException je) {
           je.printStackTrace();
       }

       // you can also print the errors/warning explicitly (instead of debug='true' in xml)
       //StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}


来源:https://stackoverflow.com/questions/8482359/programmatically-enable-logback-in-debug-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!