登录Grails:使用Log4j2重新加载外部配置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了登录Grails:使用Log4j2重新加载外部配置相关的知识,希望对你有一定的参考价值。
我正在尝试配置Grails,以便使用分离生产和开发模式的外部Log4j2配置文件。它应该监听配置更改并在一段时间后刷新它。对于Grails 2.x,可以通过注册Log4jConfigurer
bean来完成,如下所示:
switch (Environment.current) {
case Environment.PRODUCTION:
log4jConfigurer(MethodInvokingFactoryBean) {
targetClass = "org.springframework.util.Log4jConfigurer"
targetMethod = "initLogging"
arguments = ["classpath:ogc-log4j.xml", 30000]
}
case Environment.DEVELOPMENT:
log4jConfigurer(MethodInvokingFactoryBean) {
targetClass = "org.springframework.util.Log4jConfigurer"
targetMethod = "initLogging"
arguments = ["classpath:log4j-dev.xml", 30000]
}
}
出于某些原因,这种方法在Grails 3.x中不起作用。我怎样才能在Grails 3.3.3或Spring Boot中执行此操作(我想它应该可以工作,因为Grails 3.x基于Spring Boot)?
从3.3.3的grails
而不是在Java代码中。环境配置已移至YML配置文件。
我们可以将不同的值传递给不同的环境并更改log4j的配置
请参阅文档
documentaion for Enviroment configuration
我认为我们可以用不同的方法达到预期的需求。据我所知,在Grails 3中外化Log4j2
配置文件,我们可以使用LogerContext
或System.setProperty
。后者可以按照post的指示完成。我的建议,以及这个问题的演示,是使用LogerContext
的Logging Separation部分所描述的Log4j2 manual。
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.core.LoggerContext
class BootStrap {
def init = { servletContext ->
LoggerContext context = (LoggerContext) LogManager.getContext(false)
String userHome = System.getProperty("user.home")
String pathname = ""
if (grails.util.Environment.isDevelopmentMode()) {
pathname = userHome + "/.myConfigurations/log4j2-dev.xml"
} else {
pathname = userHome + "/.myConfigurations/log4j2-prod.xml"
}
File file = new File(pathname)
// this will force a reconfiguration
context.setConfigLocation(file.toURI())
}
}
请看看上传到Bitbucket的my project。在这个项目中,我尝试在启动应用程序后记录消息。 log.info
被称为Application.groovy
。在grails 3.3.9中启动应用程序,您必须运行run-app
来测试开发或prod run-app
来测试生产模式。
以上是关于登录Grails:使用Log4j2重新加载外部配置的主要内容,如果未能解决你的问题,请参考以下文章
如何从 grails 3.1.8 中的外部文件加载数据源配置?