开发者

Is it possible to find logback log files programmatically?

It would be useful to automatically attach log files to support emails. I could set the path programmatica开发者_开发知识库lly (as in Setting Logback Appender path programmatically), but I'd prefer to let users configure logging in the familiar way via logback.xml. So, can I find the files logback uses for logging?


You can get the list of all appenders in a certain context. To do this:

LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
for (Logger logger : context.getLoggerList()) {
        for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders(); index.hasNext();) {
            Appender<ILoggingEvent> appender = index.next();
        }
    }

This iterates over the list of all appenders in all loggers for the current context.


Answer given by @tafoo85 is correct one but it will give you appenders only.

To more specific get file used by Logback logger i hope below code will help some one.

File clientLogFile;
FileAppender<?> fileAppender = null;
LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
for (Logger logger : context.getLoggerList())
{
     for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders();
                 index.hasNext();)
     {
           Object enumElement = index.next();
           if (enumElement instanceof FileAppender) {
                fileAppender=(FileAppender<?>)enumElement;
           }
     }
}

if (fileAppender != null) {
     clientLogFile=new File(fileAppender.getFile());
}
else {
     clientLogFile = null;
}

Log.d("logfile path", clientLogFile.getAbsolutePath());


You can get the actual file like so:

    LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();

    for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
        for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders(); index.hasNext();) {
            Appender<ILoggingEvent> appender = index.next();

            if (appender instanceof FileAppender) {
                FileAppender<ILoggingEvent> fa = (FileAppender<ILoggingEvent>)appender;
                ResilientFileOutputStream rfos = (ResilientFileOutputStream)fa.getOutputStream();
                File file = rfos.getFile();

                System.out.println(file.getAbsolutePath());
            }
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜