![](/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.