以编程方式设置 Logback Appender 路径 [英] Setting Logback Appender path programmatically

查看:41
本文介绍了以编程方式设置 Logback Appender 路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式设置 Logback appender 路径.(RollingFileAppender 确切地说是 FixedWindowRollingPolicy)

I'm trying to set Logback appender path programmatically. (RollingFileAppender with FixedWindowRollingPolicy to be exact)

我这样做是因为我想让我的用户在首选项对话框 (Eclipse RCP) 中设置日志路径

I'm doing this because I want to enable my users to set the log path in a preference dialog (Eclipse RCP)

我已经尝试过类似的方法,但我没有更改配置文件中定义的日志路径:

I've tried something like this, but I doesn't change the log path from what's defined in the configuration file:

Logger logback_logger = (ch.qos.logback.classic.Logger)LoggerFactory
   .getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
RollingFileAppender<ILoggingEvent> rfappender = 
   (RollingFileAppender<ILoggingEvent>)logback_logger.getAppender("FILE");
rfappender.setFile(newFile);
FixedWindowRollingPolicy rollingPolicy = 
   (FixedWindowRollingPolicy)rfappender.getRollingPolicy();
rollingPolicy.setFileNamePattern(newPattern);

推荐答案

使用系统属性并重新加载配置文件似乎更清晰:

Using system properties and reloading the configuration file seems cleaner:

更改 logback.xml 文件:

change the logback.xml file:

<file>${log_path:-}myfile.log</file>
....
<FileNamePattern>${log_path:-}myfile.%i.log</FileNamePattern>

这会将默认位置设置为工作目录.然后,使用:

This will set the default location to the working directory. Then, use:

System.setProperty("log_path", my_log_path);

//Reload:
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
ContextInitializer ci = new ContextInitializer(lc);
lc.reset();
try {
  //I prefer autoConfig() over JoranConfigurator.doConfigure() so I wouldn't need to find the file myself.
  ci.autoConfig(); 
} catch (JoranException e) {
  // StatusPrinter will try to log this
  e.printStackTrace();
}
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);

这篇关于以编程方式设置 Logback Appender 路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆