It would be useful to automatically attach log files to support emails. I could set the path programmatically (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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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.
回答2:
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());
回答3:
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());
}
}
}