开发者

Logback Groovy Config to use JMX?

On Logback's documentation, they make putting JMX info into the XML file seem easy:

http://logback.qos.ch/manual/jmxConfig.html

But all their examples are using their XML configuration and I want to use Groovy. There is no mention of JMX Configurator in their Groovy DSL documentation:

http://logback.qos.ch/manual/groovy.html

So I copied the first JMX/XML example in their XML to Groovy translator.

The XML:

    <configuration>
         <jmxConfigurator />

         <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
           <layout class="ch.qos.logback.classic.PatternLayout">
             <Pattern>%date [%thread] %-5level %logger{25} - %msg%n</Pattern>
           </layout>
        </appender>

        <root level="debug">
         <appender-ref ref="console" />
        </root>  
 </configuration>

The translator:

http://logback.qos.ch/translator/asGroovy.html

And the result:

import ch.qos.logback.classic.PatternLayout
import ch.qos.log开发者_StackOverflow中文版back.core.ConsoleAppender

import static ch.qos.logback.classic.Level.DEBUG

appender("console", ConsoleAppender) {
   layout(PatternLayout) {
   pattern = "%date [%thread] %-5level %logger{25} - %msg%n"
 }
}
root(DEBUG, ["console"])

And it didn't do anything with JMX -- just put in the console appender.

Any ideas what I need to do?


The configurator to parse the Groovy-based configuration files, doesn't support the jmxConfigurator as in the XML-based configuration files. But we can still write a method in our Groov configuration file to initialize the JMX Configurator.

If we look at the source code of Logback we see that the file ch.qos.logback.classic.joran.action.JMXConfigurationAction does the stuff to set up JMX from the XML-based configuration. We can use this code as a sample for the Groovy version.

def jmxConfigurator() {
    def contextName = context.name
    def objectNameAsString = MBeanUtil.getObjectNameFor(contextName, JMXConfigurator.class)
    def objectName = MBeanUtil.string2ObjectName(context, this, objectNameAsString)
    def platformMBeanServer = ManagementFactory.getPlatformMBeanServer()
    if (!MBeanUtil.isRegistered(platformMBeanServer, objectName)) {
        JMXConfigurator jmxConfigurator = new JMXConfigurator((LoggerContext) context, platformMBeanServer, objectName)
        try {
            platformMBeanServer.registerMBean(jmxConfigurator, objectName)
        } catch (all) {
            addError("Failed to create mbean", all)
        }
    }
}

jmxConfigurator()

I haven't tested this code myself, but I hope the general idea is clear.


Logback added support for JMX configuration in the Groovy config in 2013:

You can register a JMXConfigurator MBean (using Logback's default ObjectName ), by adding the following to your logback.groovy:

jmxConfigurator()

More details and overloads of this method in the manual.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜