Fork me on GitHub

Instrumenting Log4j

The metrics-log4j2 module provide InstrumentedAppender, a Log4j Appender implementation which records the rate of logged events by their logging level. You can add it to the root logger programmatically.

Filter filter = null;        // That's fine if we don't use filters;
PatternLayout layout = null; // The layout isn't used in InstrumentedAppender

InstrumentedAppender appender = new InstrumentedAppender(metrics, filter, layout, false);

LoggerContext context = (LoggerContext) LogManager.getContext(false);
Configuration config = context.getConfiguration();
config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).addAppender(appender, level, filter);

You can also use standard log4j2 configuration, via plugin support:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO" name="log4j2-config" packages="com.codahale.metrics.log4j2">
    <MetricsAppender name="metrics" registryName="shared-metrics-registry"/>
    <Root level="INFO">
        <AppenderRef ref="metrics" />