Fork me on GitHub

Instrumenting Log4j

The metrics-log4j and metrics-log4j2 modules provide InstrumentedAppender, a Log4j Appender implementation (for log4j 1.x and log4j 2.x correspondingly) which records the rate of logged events by their logging level.

You can add it to the root logger programmatically.

For log4j 1.x:

InstrumentedAppender appender = new InstrumentedAppender(registry);

For log4j 2.x:

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" />