![](/img/trans.png)
[英]Is it possible to reload log4j.xml / log4j.properties file dynamically in Tomcat?
[英]Dynamically reload log4j.properties for grails application running in tomcat
我有一個grails應用程序,已部署到tomcat,使用的是log4j。 我希望能夠在tomcat中更新/webapps/WEB-INF/classes/log4j.properties,然后讓應用程序動態地獲取更改而無需重新啟動。 我還沒有運氣找到這樣做的好方法。 我發現的是:
我可以將文件作為流檢索:
Thread.currentThread().getContextClassLoader().getResourceAsStream("log4j.properties")
不幸的是,這是啟動期間加載的類,我不確定是否/如何強制其從實際文件中更新。 如果可行,我可以閱讀每個屬性並使用:
Logger.rootLogger.loggerRepository.getLogger(<key>).level = <new log level>
我已經看到了有關LogManager.resetConfiguration()
但這似乎也無濟於事。
另外,這就是我在resources.groovy
設置log4j的方式
beans = {
// Setting up external configuration for log4j
log4jConfigurer(org.springframework.beans.factory.config.MethodInvokingFactoryBean) {
targetClass = "org.springframework.util.Log4jConfigurer"
targetMethod = "initLogging"
arguments = ["classpath:log4j.properties"]
}
}
當我了解它的漏洞時,我對使用configureAndWatch
方法不感興趣。
我看到有可以用於log4j的XML和JSON屬性,而我只是使用一個普通的* .properties文件,我不確定這是否是問題的一部分。
任何提示將不勝感激,在此先感謝!
以下是解決此問題的方法,它需要setUseCaches(false),以確保未使用文件的緩存版本(來自類加載器)。
def fileInputStream = null
// The method below is used to ensure that the file is read from disk every time, rather than using the previously loaded file from the ClassLoader
def classLoader = Thread.currentThread().getContextClassLoader()
def resource = classLoader.getResource("log4j.properties")
def connection = resource.openConnection()
connection.setUseCaches(false)
// Warning: do not read or log the fileInputStream, because it will close the connection
fileInputStream = (FileInputStream)connection.getInputStream().in
// Use the Properties object to prevent errors on comments (#)
def props = new Properties()
props.load(fileInputStream)
def config = new ConfigSlurper().parse(props)
然后,我可以使用以下方式引用記錄器屬性:
config.log4j.logger.each {
Logger.rootLogger.loggerRepository.getLogger(it.key).level = Level.toLevel(it.value)
}
您還可以進行檢查以查看現有的日志級別是什么,並提供輸出以表明實際更改了哪些日志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.