登录Grails:使用Log4j2重新加载外部配置

问题描述 投票:0回答:2

我正在尝试配置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)?

spring spring-boot grails log4j grails3
2个回答
1
投票

从3.3.3的grails

而不是在Java代码中。环境配置已移至YML配置文件。

我们可以将不同的值传递给不同的环境并更改log4j的配置

请参阅文档

documentaion for Enviroment configuration


0
投票

我认为我们可以用不同的方法达到预期的需求。据我所知,在Grails 3中外化Log4j2配置文件,我们可以使用LogerContextSystem.setProperty。后者可以按照post的指示完成。我的建议,以及这个问题的演示,是使用LogerContextLogging 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来测试生产模式。

© www.soinside.com 2019 - 2024. All rights reserved.