[英]Setting logback.xml path programmatically
我知道我可以像這樣設置logback.xml路徑:
將默認配置文件的位置指定為系統屬性
您可以使用名為“logback.configurationFile”的系統屬性指定默認配置文件的位置。 此屬性的值可以是URL,類路徑上的資源或應用程序外部文件的路徑。
java -Dlogback.configurationFile=/path/to/config.xml chapters.configuration.MyApp1
但我怎么能在代碼中做到這一點?
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
JoranConfigurator configurator = new JoranConfigurator();
InputStream configStream = FileUtils.openInputStream(logbackPropertiesUserFile);
configurator.setContext(loggerContext);
configurator.doConfigure(configStream); // loads logback file
configStream.close();
你可以使用:
System.setProperty("logback.configurationFile", "/path/to/config.xml");
但它必須在加載logback之前發生,例如:
class Main {
static { System.setProperty("logback.configurationFile", "/path/to/config.xml");}
private final Logger LOG = LoggerFactory.getLogger(Main.class);
public void main (String[] args) { ... }
}
注意:我沒有測試過,但應該可以使用。
修改環境變量可能並不總是可行的。 要正確地看到回滾手冊:
http://logback.qos.ch/manual/configuration.html#joranDirectly
我只想分享我最終使用Jersey-Spring應用程序做的事情:
MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
servletContext.addListener(new LogbackConfigListener());
try { LogbackConfigurer.initLogging(servletContext.getRealPath("/WEB-INF/logback.xml")); }
catch (FileNotFoundException | JoranException e) { e.printStackTrace(); }
}
}
我還必須補充一點,我必須搬家
<dependency>
<groupId>org.logback-extensions</groupId>
<artifactId>logback-ext-spring</artifactId>
<version>0.1.4</version>
<scope>compile</scope></dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
<scope>compile</scope></dependency>
從運行時(在我的案例中為父項目)進行編譯。
包含另一個logback xml以更改logback-spring.xml中的路徑
include resource =“/ path / to / logback.xml”
在logback.xml中添加包含標記內的數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.