【问题标题】:log4 properties injection in grails Config.groovygrails Config.groovy 中的 log4 属性注入
【发布时间】:2014-01-23 14:28:23
【问题描述】:

我想注入存储在我的 Config.groovy 的属性文件中的 log4j 配置内容。

这是我的属性文件:

log.file=path/to/my/log
log.root.level=info
log.grails.app.level=info

文件路径 EL 语法 ${} 没有问题,但它不适用于关卡,因为它不是字符串。这是 config.groovy :

appenders {
    file name:'file', file:"${config.log.file}"
}

root {
    ${log.root.level} 'stdout', 'file'
}

有什么建议吗?

【问题讨论】:

    标签: grails log4j


    【解决方案1】:

    您必须读取属性文件并将其转换为 ConfigObject 以在 Config.groovy 中使用。

    log4j {
        def props = new Properties()
        new File("path/to/log.properties").withReader{
            props.load(it)
        }
        def slurp = new ConfigSlurper().parse(props)
    
        appenders {
            file name:'file', file:"$slurp.log.file"
        }
    
        root {
            "$slurp.log.root.level" 'stdout', 'file'
        }
    }
    

    请参阅此similar question

    【讨论】:

    • 谢谢,我现在可以加载我的属性,但是当服务器启动时,配置 log4j 日志时出现 异常:没有方法签名:groovy.util.ConfigObject.level() 是适用于参数类型:(java.lang.String, java.lang.String) 值:[stdout, file]
    • 我的错。错过了引号。更新了答案。
    • 它有效,谢谢。我不完全理解双引号的技巧,我对 Groovy/Grails 世界很陌生...
    【解决方案2】:

    如果我正确阅读了 Grails Log4J DSL parser 的代码,您应该可以说

    root {
        "${config.config.log.root.level}" 'stdout', 'file'
    }
    

    或者如果这不起作用,那么

    root {
        delegate."${config.config.log.root.level}" 'stdout', 'file'
    }
    

    通常,在log4j 闭包中,您可以访问完整的grailsApplication.config(包括从外部配置文件中合并的选项)作为变量config,但看起来您需要在前面添加第二个config当你在 root {} 块内时。

    解释 - root 闭包的闭包委托是一个 RootLog4jConfig 对象,它有一个属性 config 指向主 Log4jConfig,它是 log4j 其余部分的委托闭包,而它又拥有自己的属性config,指向解析后的ConfigObject。我不知何故怀疑这种行为是故意的,可能值得 JIRA 建议 config 应该在 root 块内解决与它外部相同的事情。

    【讨论】:

    • 我已经尝试了这两种解决方案。服务器启动时没有输出日志和此消息 log4j:ERROR 配置 log4j 时缺少属性:log
    • @LaurentBOURGEOIS 要使config. 工作,您必须在grails.config.locations 中列出外部属性文件
    • 属性文件已经在我的 config.locations def envName = System.properties.getProperty("tomcat.server.name") grails.config.locations = ["classpath:"+envName+"-config.properties"]
    • @LaurentBOURGEOIS 嗯,检查the code 看起来config.config.log.root.level 可能有效——与在根闭包外部相比,您需要在根闭包内部添加一个额外的“配置”。我怀疑这是故意的......
    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多