代码之家  ›  专栏  ›  技术社区  ›  Taras Kohut

登录Grails:Log4j2的可重新加载外部配置

  •  0
  • Taras Kohut  · 技术社区  · 7 年前

    我正在尝试配置Grails,以便使用分离生产和开发模式的外部Log4j2配置文件。它应该监听配置更改,并在一段时间后刷新。 对于Grails 2。x、 可以通过注册来完成 Log4jConfigurer

    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、 我如何在Grails3.3.3或Spring Boot中做到这一点(我想应该可以,因为Grails3.x是基于Spring Boot的)?

    0 回复  |  直到 7 年前
        1
  •  1
  •   Akhil Surapuram    7 年前

    来自grails的3.3.3

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

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

    documentaion for Enviroment configuration

        2
  •  0
  •   Tung    7 年前

    我认为我们可以通过不同的方法来达到预期的需求。就我所知,外部化 Log4j2 在Grails 3中的配置文件中,我们可以使用 LogerContext System.setProperty . 后者可以按照 post . 我的建议,以及这个问题的演示,是使用 如中所述 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())
        }
    }
    

    请看一下 my project 已上载到Bitbucket。在这个项目中,我尝试在启动应用程序后记录一条消息。这个 log.info 被叫进来了 Application.groovy . 在grails 3.3.9中启动应用程序,您必须运行 run-app 测试开发或 prod run-app