Skip to content

Commit

Permalink
fix #301 Add Http Server Access Log
Browse files Browse the repository at this point in the history
  • Loading branch information
violetagg committed Sep 4, 2018
1 parent f778f53 commit e26831e
Show file tree
Hide file tree
Showing 4 changed files with 200 additions and 13 deletions.
2 changes: 1 addition & 1 deletion src/main/java/reactor/ipc/netty/NettyPipeline.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ public interface NettyPipeline {
String ReactiveBridge = RIGHT + "reactiveBridge";
String HttpCodec = LEFT + "httpCodec";
String HttpDecompressor = LEFT + "decompressor";
String HttpCompressor = LEFT + "compressor";
String HttpAggregator = LEFT + "httpAggregator";
String HttpServerHandler = LEFT + "httpServerHandler";
String AccessLogHandler = LEFT + "accessLogHandler";
String OnChannelWriteIdle = LEFT + "onChannelWriteIdle";
String OnChannelReadIdle = LEFT + "onChannelReadIdle";
String ChunkedWriter = LEFT + "chunkedWriter";
Expand Down
166 changes: 166 additions & 0 deletions src/main/java/reactor/ipc/netty/http/server/AccessLogHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/*
* Copyright (c) 2011-2018 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package reactor.ipc.netty.http.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufHolder;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.LastHttpContent;
import reactor.util.Logger;
import reactor.util.Loggers;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Objects;

/**
* @author Violeta Georgieva
*/
final class AccessLogHandler extends ChannelDuplexHandler {

AccessLog accessLog = new AccessLog();

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
final HttpRequest request = (HttpRequest) msg;

accessLog = new AccessLog()
.address(((SocketChannel) ctx.channel()).remoteAddress().getHostString())
.method(request.method().name())
.uri(request.uri())
.protocol(request.protocolVersion().text());
}
super.channelRead(ctx, msg);
}

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (msg instanceof HttpResponse) {
final HttpResponse response = (HttpResponse) msg;
HttpResponseStatus status = response.status();
if (status.equals(HttpResponseStatus.CONTINUE)) {
ctx.write(msg, promise);
return;
}
boolean chunked = HttpUtil.isTransferEncodingChunked(response);
accessLog.status(status.code())
.chunked(chunked);
if (!chunked) {
accessLog.contentLength(HttpUtil.getContentLength(response, -1));
}
}
if (msg instanceof LastHttpContent) {
accessLog.increaseContentLength(((LastHttpContent) msg).content().readableBytes());
ctx.write(msg, promise)
.addListener(future -> {
if (future.isSuccess()) {
accessLog.log();
}
});
return;
}
if (msg instanceof ByteBuf) {
accessLog.increaseContentLength(((ByteBuf) msg).readableBytes());
}
if (msg instanceof ByteBufHolder) {
accessLog.increaseContentLength(((ByteBufHolder) msg).content().readableBytes());
}
ctx.write(msg, promise);
}

static final class AccessLog {
static final Logger log = Loggers.getLogger("reactor.netty.http.server.AccessLog");
static final DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.US);
static final String COMMON_LOG_FORMAT =
"{} - {} [{}] \"{} {} {}\" {} {}";
static final String MISSING = "-";

final String zonedDateTime;

String address;
String method;
String uri;
String protocol;
String user = MISSING;
int status;
long contentLength;
boolean chunked;

AccessLog() {
this.zonedDateTime = ZonedDateTime.now().format(DATE_TIME_FORMATTER);
}

AccessLog address(String address) {
this.address = Objects.requireNonNull(address, "address");
return this;
}

AccessLog method(String method) {
this.method = Objects.requireNonNull(method, "method");
return this;
}

AccessLog uri(String uri) {
this.uri = Objects.requireNonNull(uri, "uri");
return this;
}

AccessLog protocol(String protocol) {
this.protocol = Objects.requireNonNull(protocol, "protocol");
return this;
}

AccessLog status(int status) {
this.status = status;
return this;
}

AccessLog contentLength(long contentLength) {
this.contentLength = contentLength;
return this;
}

AccessLog increaseContentLength(long contentLength) {
if (chunked) {
this.contentLength += contentLength;
}
return this;
}

AccessLog chunked(boolean chunked) {
this.chunked = chunked;
return this;
}

void log() {
if (log.isInfoEnabled()) {
log.info(COMMON_LOG_FORMAT, address, user, zonedDateTime,
method, uri, protocol, status, (contentLength > -1 ? contentLength : MISSING));
}
}
}
}
29 changes: 18 additions & 11 deletions src/main/java/reactor/ipc/netty/http/server/HttpServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,9 @@ public void startRouterAndAwait(Consumer<? super HttpServerRoutes> routesBuilder

static final LoggingHandler loggingHandler = new LoggingHandler(HttpServer.class);

static final boolean ACCESS_LOG_ENABLED =
Boolean.parseBoolean(System.getProperty("reactor.netty.http.server.accessLogEnabled", "false"));

static BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate(
HttpServerOptions options) {

Expand Down Expand Up @@ -309,17 +312,21 @@ protected ContextHandler<Channel> doHandler(
.autoCreateOperations(false);
}

@Override
public void accept(ChannelPipeline p, ContextHandler<Channel> c) {
p.addLast(NettyPipeline.HttpCodec, new HttpServerCodec(
options.httpCodecMaxInitialLineLength(),
options.httpCodecMaxHeaderSize(),
options.httpCodecMaxChunkSize(),
options.httpCodecValidateHeaders(),
options.httpCodecInitialBufferSize()));

p.addLast(NettyPipeline.HttpServerHandler, new HttpServerHandler(c));
}
@Override
public void accept(ChannelPipeline p, ContextHandler<Channel> c) {
p.addLast(NettyPipeline.HttpCodec, new HttpServerCodec(
options.httpCodecMaxInitialLineLength(),
options.httpCodecMaxHeaderSize(),
options.httpCodecMaxChunkSize(),
options.httpCodecValidateHeaders(),
options.httpCodecInitialBufferSize()));

if (ACCESS_LOG_ENABLED) {
p.addLast(NettyPipeline.AccessLogHandler, new AccessLogHandler());
}

p.addLast(NettyPipeline.HttpServerHandler, new HttpServerHandler(c));
}

@Override
protected LoggingHandler loggingHandler() {
Expand Down
16 changes: 15 additions & 1 deletion src/test/resources/logback.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,22 @@
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!-- Access Log configuration
<appender name="accessLog" class="ch.qos.logback.core.FileAppender">
<file>access_log.log</file>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<appender name="async" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="accessLog" />
</appender>
<logger name="reactor.netty.http.server.AccessLog" level="INFO" additivity="false">
<appender-ref ref="async"/>
</logger> -->

<!--<logger name="reactor" level="DEBUG"/>-->
<!--<logger name="reactor" level="DEBUG"/>-->
<!--<logger name="reactor" level="INFO"/>-->
<logger name="reactor.ipc.netty" level="DEBUG" />
<!--<logger name="reactor.ipc.netty.http.client.HttpClient" level="DEBUG" />-->
Expand Down

0 comments on commit e26831e

Please sign in to comment.