Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting a Log4J appender into a Grails application

Tags:

grails

log4j

I'm making a simple grails plugin that'll act as central configuration for our companies various projects' logging. The general idea is that you simply add the plugin to your project, and it'll inject the various appenders to the root logger. I'm testing this first with a Graylog2 appender (which works if I just configure it in Config.groovy). This is the code I've tried (in the init() of BootStrap.groovy [which gets executed on startup]:

    def rL = Logger.rootLogger
    def layout = new PatternLayout(conversionPattern: '%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %c{1} - %m%n')

    Appender appender = new org.graylog2.log.GelfAppender(
            name:"gelf",
            graylogHost:"graylog2.ourcompany.com",
            extractStacktrace: true,
            addExtendedInformation: true,
            facility: "gelf-java",
            threshold: org.apache.log4j.Level.INFO,
            additionalFields: "{'runtime': 'grails', 'environment': 'dev', 'transport': 'gelf-java'}",
            layout: layout
    )
    rL.addAppender(appender)

The appender is correctly instantiated and attached to the root logger, here is output from rL.getAllAppenders().toList().each { print it.toString() } :

org.codehaus.groovy.grails.plugins.log4j.appenders.GrailsConsoleAppender@7a054197
org.graylog2.log.GelfAppender@6f155f16

So, despite the Appender being added to the root logger, and Error-level messages being written to the log (and displayed to the default Console Logger), it simply does not fire off the messages to Graylog2 (I've checked using Wireshark to verify this). This works fine if I just set the values in a Config.groovy of another project; but obviously that defeats the purpose of this plugin.

like image 655
Noxville Avatar asked Nov 13 '22 02:11

Noxville


1 Answers

You need to call activateOptions() on your appender before you add it to the root logger. Grails does this for you when you configure the appender in Config.groovy which is why it worked there.

like image 185
Ian Roberts Avatar answered Jun 13 '23 22:06

Ian Roberts