我有一个部署到 tomcat 的 grails 应用程序,它使用 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
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
方法不感兴趣,因为我已经了解了它的漏洞。
我看到有 XML 和 JSON 属性可以用于 log4j,而我只是使用一个普通的 *.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)
}
您还可以检查现有的日志级别,并提供输出以说明哪些日志记录已实际更改。
关于tomcat - 为在 tomcat 中运行的 grails 应用程序动态重新加载 log4j.properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20380481/