我们正在尝试向dropwizard访问日志添加自定义http标头。我们尝试了dropwizard 0.9.1和0.9.2,但无法找到实现此目的的方法。我们注意到以下几点:
有没有办法记录这些信息?
答案 0 :(得分:0)
可以使用自定义org.eclipse.jetty.server.RequestLog
实现,可以通过扩展io.dropwizard.jetty.RequestLogFactory
并替换ServerFactory中的dropwizard实现来注册到jetty。这里有一个可能的实现:
import ch.qos.logback.classic.*;
import ch.qos.logback.classic.spi.*;
import ch.qos.logback.core.*;
import ch.qos.logback.core.spi.*;
import com.google.common.collect.ImmutableList;
import io.dropwizard.jetty.*;
import io.dropwizard.logging.*;
import org.eclipse.jetty.server.*;
import org.slf4j.LoggerFactory;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Enumeration;
import java.util.TimeZone;
public class CustomRequestLogFactory extends RequestLogFactory {
@NotNull
private TimeZone timeZone = TimeZone.getTimeZone("UTC");
@Valid
@NotNull
private ImmutableList<AppenderFactory> appenders = ImmutableList.<AppenderFactory>of(
new ConsoleAppenderFactory()
);
private static class RequestLogLayout extends LayoutBase<ILoggingEvent> {
@Override
public String doLayout(ILoggingEvent event) {
return event.getFormattedMessage() + CoreConstants.LINE_SEPARATOR;
}
}
private static class CustomRequestLog extends Slf4jRequestLog {
private static Logger logger = (Logger) LoggerFactory.getLogger(CustomRequestLog.class);
private static ThreadLocal<StringBuilder> _buffers = new ThreadLocal<StringBuilder>() {
@Override
protected StringBuilder initialValue() {
return new StringBuilder(256);
}
};
public CustomRequestLog(AppenderAttachableImpl<ILoggingEvent> appenders,
TimeZone timeZone) {
super(appenders, timeZone);
}
@Override
public void log(Request request, Response response) {
StringBuilder buf = _buffers.get();
buf.setLength(0);
buf.append(request.getServerName()).append('\n');
Enumeration<String> headers = request.getHeaderNames();
while (headers.hasMoreElements()) {
String header = headers.nextElement();
buf.append(header).append('=')
.append(request.getHeader(header)).append('\n');
}
try {
write(buf.toString());
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
public RequestLog build(String name) {
final Logger logger = (Logger) LoggerFactory.getLogger("http.request");
logger.setAdditive(false);
final LoggerContext context = logger.getLoggerContext();
final RequestLogLayout layout = new RequestLogLayout();
layout.start();
final AppenderAttachableImpl<ILoggingEvent> attachable =
new AppenderAttachableImpl<>();
for (AppenderFactory output : this.appenders) {
attachable.addAppender(output.build(context, name, layout));
}
return new CustomRequestLog(attachable, timeZone);
}
}
在ServerFactory中设置RequestLogFactory:
@Override
public void run(ApplicationConfiguration configuration,
Environment environment) {
...
((DefaultServerFactory) configuration.getServerFactory())
.setRequestLogFactory(new CustomRequestLogFactory());
}