Skip to content

Instantly share code, notes, and snippets.

@ajmath
Last active August 19, 2022 19:11
Show Gist options
  • Save ajmath/e9f90c29cd224653c218 to your computer and use it in GitHub Desktop.
Save ajmath/e9f90c29cd224653c218 to your computer and use it in GitHub Desktop.
Dropwizard Custom Appender
server:
type: default
requestLog:
appenders:
- type: console-json
name: request-log-console-json
includeContextName: false
logging:
level: INFO
appenders:
- type: console-json
package io.github.ajmath;
import io.dropwizard.logging.AbstractAppenderFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.contrib.jackson.JacksonJsonFormatter;
import ch.qos.logback.contrib.json.classic.JsonLayout;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
@JsonTypeName("console-json")
public class ConsoleJsonAppenderFactory extends AbstractAppenderFactory {
private String appenderName = "console-json-appender";
private boolean includeContextName = true;
@JsonProperty
public String getName() {
return this.appenderName;
}
@JsonProperty
public void setName(String name) {
this.appenderName = name;
}
@JsonProperty
public boolean getIncludeContextName() {
return this.includeContextName;
}
@JsonProperty
public void setIncludeContextName(boolean includeContextName) {
this.includeContextName = includeContextName;
}
@Override
public Appender<ILoggingEvent> build(LoggerContext context, String applicationName, Layout<ILoggingEvent> providedLayout) {
JsonLayout layout = new JsonLayout();
layout.setJsonFormatter(new JacksonJsonFormatter());
layout.setAppendLineSeparator(true);
layout.setTimestampFormatTimezoneId("UTC");
layout.setIncludeContextName(includeContextName);
LayoutWrappingEncoder<ILoggingEvent> layoutEncoder = new LayoutWrappingEncoder<>();
layoutEncoder.setLayout(layout);
ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
appender.setName(appenderName);
appender.setContext(context);
appender.setEncoder(layoutEncoder);
addThresholdFilter(appender, threshold);
appender.start();
return wrapAsync(appender);
}
}
# Placed in src/main/resources/META-INF/services/io.dropwizard.logging.AppenderFactory without this line
io.dropwizard.logging.ConsoleAppenderFactory
io.dropwizard.logging.FileAppenderFactory
io.dropwizard.logging.SyslogAppenderFactory
io.github.ajmath.ConsoleJsonAppenderFactory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment