自动附加日志文件以支持电子邮件会很有用。我可以通过编程方式设置路径(如Setting Logback Appender path programmatically中所述),但我更愿意让用户通过logback.xml
以熟悉的方式配置日志记录。那么,我能找到logback用于记录的文件吗?
答案 0 :(得分:31)
您可以获取特定上下文中所有appender的列表。要做到这一点:
LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
for (Logger logger : context.getLoggerList()) {
for (Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders(); index.hasNext();) {
Appender<ILoggingEvent> appender = index.next();
}
}
这将迭代当前上下文的所有记录器中的所有appender列表。
答案 1 :(得分:19)
@ tafoo85给出的答案是正确的,但它只会给你appenders。
对于Logback logger使用的更具体的get文件,我希望下面的代码可以帮助一些人。
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());
答案 2 :(得分:2)
您可以像这样获取实际文件:
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());
}
}
}