Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fedotxxl
Created June 28, 2016 14:36
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save fedotxxl/0b3cc5e5e4eaeffdcde1f9834796edc6 to your computer and use it in GitHub Desktop.
Save fedotxxl/0b3cc5e5e4eaeffdcde1f9834796edc6 to your computer and use it in GitHub Desktop.
package com.devadmin.utils.dropwizard;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.util.ContextInitializer;
import ch.qos.logback.core.joran.spi.JoranException;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.dropwizard.logging.LoggingFactory;
import io.dropwizard.logging.LoggingUtil;
/**
* https://github.com/dropwizard/dropwizard/issues/1567
* Override getLoggingFactory for your configuration
*/
public class LogbackAutoConfigLoggingFactory implements LoggingFactory {
@JsonIgnore
private LoggerContext loggerContext;
@JsonIgnore
private final ContextInitializer contextInitializer;
public LogbackAutoConfigLoggingFactory() {
this.loggerContext = LoggingUtil.getLoggerContext();
this.contextInitializer = new ContextInitializer(loggerContext);
}
@Override
public void configure(MetricRegistry metricRegistry, String name) {
try {
contextInitializer.autoConfig();
} catch (JoranException e) {
throw new RuntimeException(e);
}
}
@Override
public void stop() {
loggerContext.stop();
}
}
@krolen
Copy link

krolen commented Oct 31, 2017

between lines 29 and 30 it would be better to add
loggerContext.reset();
so logging context would not be initialized two times and though a user will not see an each message twice.

@s-lindenau
Copy link

Also the stop implementation should not call loggerContext.stop().
This disables all logging, which is not what you want usually ;).

The javadoc of io.dropwizard.logging.LoggingFactory#stop says:
/** Should flush all log messages but not disable logging */

You can check what Dropwizard itself does in io.dropwizard.logging.DefaultLoggingFactory#stop if you want to see how to achieve that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment