Log4j filter in Grails Log4j DSL configuration

2019-02-19 19:13发布

问题:

Is there a way to specify a log4j filter in Grails log4j DSL configuration? I need to define something like this in my Grails log4j config:

<filter class="org.apache.log4j.filter.ExpressionFilter">
    <param name="expression" value="EXCEPTION ~= com.company.BackendNotAvailableException" />
    <param name="acceptOnMatch" value="false"/>
</filter>

I use Grails 1.3.7.

回答1:

I have worked around this issue by adding a short init code to Bootstrap.groovy

Logger.rootLogger.allAppenders.each { appender ->
    ExpressionFilter filter = new ExpressionFilter()
    filter.expression = "EXCEPTION ~= org.springframework.security.authentication.*"
    filter.acceptOnMatch = false
    filter.activateOptions()
    appender.addFilter(filter)
}


回答2:

Just an update, stumbled into this issue and found another solution (hope to serve this as a reference):

in Config.groovy,

Filter expFilter = new org.apache.log4j.filter.ExpressionFilter()
expFilter.setExpression('EXCEPTION ~= com.company.BackendNotAvailableException')
expFilter.setAcceptOnMatch(false)

log4j = {
    appenders {
        appender new DailyRollingFileAppender(
            ...
            // This is where we set the filter:
            headFilter: expFilter
            ...
        )
}


回答3:

Thank you for your pointer. I did the same thing without an ExpressionFilter, so that I wouldn't have to load the additional Log4j Extras module, using a quick Groovy closure coercion:

import org.apache.log4j.Logger
import org.apache.log4j.spi.Filter

Logger.rootLogger.allAppenders*.addFilter({ event ->
    event.loggerName == "some.logger.name" && event.message =~ /text to ignore/
    ? Filter.DENY : Filter.NEUTRAL
} as Filter)

In my case I wanted to filter some spurious messages generated by Hibernate on startup, so I put that code in Config.groovy, because Bootstrap would be executed too late.



标签: grails log4j