gateway、webflux、reactor-netty请求日志输出方式

目录
  • gateway、webflux、reactor-netty请求日志输出
    • 场景
    • 思路
    • 解决方案
  • spring-webflux、gateway、springboot-start-web问题
    • Spring-webflux
    • Spring-gateway

gateway、webflux、reactor-netty请求日志输出

场景

在使用spring cloud gateway时想要输出请求日志,考虑到两种实现方案

方案一

官网中使用Reactor Netty Access Logs方案,配置“-Dreactor.netty.http.server.accessLogEnabled=true”开启日志记录。

输出如下:

reactor.netty.http.server.AccessLog      :
10.2.20.177 - - [02/Dec/2020:16:41:57 +0800] "GET /fapi/gw/hi/login HTTP/1.1" 200 319 8080 626 ms

  • 优点:简单方便
  • 缺点:格式固定,信息量少

方案二

创建一个logfilter,在logfilter中解析request,并输出请求信息

  • 优点:可以自定义日志格式和内容,可以获取body信息
  • 缺点:返回信息需要再写一个filter,没有匹配到路由时无法进入到logfilter中

思路

对方案一进行改造,使其满足需求。对reactor-netty源码分析,主要涉及

  • AccessLog:日志工具,日志结构体
  • AccessLogHandler:http1.1协议日志控制,我们主要使用这个。
  • AccessLogHandler2:http2协议日志控制

代码如下:

package reactor.netty.http.server; 
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;
 
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 =
            "{} - {} [{}] \"{} {} {}\" {} {} {} {} ms";
    static final String MISSING = "-"; 
    final String zonedDateTime;
 
    String address;
    CharSequence method;
    CharSequence uri;
    String protocol;
    String user = MISSING;
    CharSequence status;
    long contentLength;
    boolean chunked;
    long startTime = System.currentTimeMillis();
    int port;
 
    AccessLog() {
        this.zonedDateTime = ZonedDateTime.now().format(DATE_TIME_FORMATTER);
    }
 
    AccessLog address(String address) {
        this.address = Objects.requireNonNull(address, "address");
        return this;
    }
 
    AccessLog port(int port) {
        this.port = port;
        return this;
    }
 
    AccessLog method(CharSequence method) {
        this.method = Objects.requireNonNull(method, "method");
        return this;
    }
 
    AccessLog uri(CharSequence uri) {
        this.uri = Objects.requireNonNull(uri, "uri");
        return this;
    }
 
    AccessLog protocol(String protocol) {
        this.protocol = Objects.requireNonNull(protocol, "protocol");
        return this;
    }
 
    AccessLog status(CharSequence status) {
        this.status = Objects.requireNonNull(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;
    }
 
    long duration() {
        return System.currentTimeMillis() - startTime;
    }
 
    void log() {
        if (log.isInfoEnabled()) {
            log.info(COMMON_LOG_FORMAT, address, user, zonedDateTime,
                    method, uri, protocol, status, (contentLength > -1 ? contentLength : MISSING), port, duration());
        }
    }
}
  • AccessLogHandler:日志控制
package reactor.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;
 
/**
 * @author Violeta Georgieva
 */
final class AccessLogHandler extends ChannelDuplexHandler {
 
    AccessLog accessLog = new AccessLog();
 
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof HttpRequest) {
            final HttpRequest request = (HttpRequest) msg;
            final SocketChannel channel = (SocketChannel) ctx.channel();
 
            accessLog = new AccessLog()
                    .address(channel.remoteAddress().getHostString())
                    .port(channel.localAddress().getPort())
                    .method(request.method().name())
                    .uri(request.uri())
                    .protocol(request.protocolVersion().text());
        }
        ctx.fireChannelRead(msg);
    }
 
    @Override
    @SuppressWarnings("FutureReturnValueIgnored")
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        if (msg instanceof HttpResponse) {
            final HttpResponse response = (HttpResponse) msg;
            final HttpResponseStatus status = response.status();
 
            if (status.equals(HttpResponseStatus.CONTINUE)) {
                //"FutureReturnValueIgnored" this is deliberate
                ctx.write(msg, promise);
                return;
            }
 
            final boolean chunked = HttpUtil.isTransferEncodingChunked(response);
            accessLog.status(status.codeAsText())
                     .chunked(chunked);
            if (!chunked) {
                accessLog.contentLength(HttpUtil.getContentLength(response, -1));
            }
        }
        if (msg instanceof LastHttpContent) {
            accessLog.increaseContentLength(((LastHttpContent) msg).content().readableBytes());
            ctx.write(msg, promise.unvoid())
               .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());
        }
        //"FutureReturnValueIgnored" this is deliberate
        ctx.write(msg, promise);
    }
}

执行顺序

AccessLogHandler.channelRead > GlobalFilter.filter > AbstractLoadBalance.choose >response.writeWith >AccessLogHandler.write

解决方案

对AccessLog和AccessLogHandler进行重写,输出自己想要的内容和样式。

AccessLogHandler中重写了ChannelDuplexHandler中的channelRead和write方法,还可以对ChannelInboundHandler和ChannelOutboundHandler中的方法进行重写,覆盖请求的整个生命周期。

spring-webflux、gateway、springboot-start-web问题

Spring-webflux

当两者一起时配置的并不是webflux web application, 仍然时一个spring mvc web application。

官方文档中有这么一段注解:

很多开发者添加spring-boot-start-webflux到他们的spring mvc web applicaiton去是为了使用reactive WebClient. 如果希望更改webApplication 类型需要显示的设置,如SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE).

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

结论一:

当两者一起时配置的并不是webflux web application, 仍然时一个spring mvc web application。但是启动不会报错,可以正常使用,但是webflux功能失效

Spring-gateway

因为gateway和zuul不一样,gateway用的是长连接,netty-webflux,zuul1.0用的就是同步webmvc。

所以你的非gateway子项目启动用的是webmvc,你的gateway启动用的是webflux. spring-boot-start-web和spring-boot-start-webflux相见分外眼红。

不能配置在同一pom.xml,或者不能在同一项目中出现,不然就会启动报错

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

结论二:

当spring-cloud-gateway和spring-boot-starer-web两者一起时配置的时候, 启动直接报错,依赖包冲突不兼容

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Spring Cloud Gateway 记录请求应答数据日志操作

    我就废话不多说了,大家还是直接看代码吧~ public class GatewayContext { public static final String CACHE_GATEWAY_CONTEXT = "cacheGatewayContext"; /** * cache json body */ private String cacheBody; /** * cache formdata */ private MultiValueMap<String, String> f

  • Spring Cloud gateway 网关如何拦截Post请求日志

    gateway版本是 2.0.1 1.pom结构 (部分内部项目依赖已经隐藏) <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.s

  • spring-cloud-gateway启动踩坑及解决

    目录 spring-cloud-gateway启动踩坑 1.webflux与mvc不兼容 2.webflux使用netty作为容器 3.后来实验了下 很坑得spring cloud gateway 异常 spring-cloud-gateway启动踩坑 本人使用的版本是2.1.2,以下只记录几个小问题,但确实实实在在的把个人恶心的要死要活的找不到办法,几经挣扎,最终解决. 更可恨的是开发的过程中,没有出现异常,后来由于项目组其它人加了依赖,不知不觉对项目的兼容造成了英雄,真的是被撞的头破血流,才

  • gateway、webflux、reactor-netty请求日志输出方式

    目录 gateway.webflux.reactor-netty请求日志输出 场景 思路 解决方案 spring-webflux.gateway.springboot-start-web问题 Spring-webflux Spring-gateway gateway.webflux.reactor-netty请求日志输出 场景 在使用spring cloud gateway时想要输出请求日志,考虑到两种实现方案 方案一 官网中使用Reactor Netty Access Logs方案,配置“-D

  • 关于log4j2的异步日志输出方式

    目录 log4j2的异步日志输出方式 第一种实现异步方式AsyncAppender 第二种实现异步方式AsyncLogger log4j2异步注意事项 log4j2异步类型 小提示 log4j2的异步日志输出方式 使用log4j2的同步日志进行日志输出,日志输出语句与程序的业务逻辑语句将在同一个线程运行. 而使用异步日志进行输出时,日志输出语句与业务逻辑语句并不是在同一个线程中运行,而是有专门的线程用于进行日志输出操作,处理业务逻辑的主线程不用等待即可执行后续业务逻辑. Log4j2中的异步日志

  • Springboot异常日志输出方式

    目录 lombok插件使用 统一异常处理 统一日志输出 配置日志级别↓ Logback日志↓ 配置logback日志↓ 安装idea彩色日志插件:grep-console 复制粘贴即可 lombok插件使用 引入依赖,在项目中使用Lombok可以减少很多重复代码的书写.比如说getter/setter/toString等方法的编写 ↓ <!--lombok用来简化实体类--> <dependency> <groupId>org.projectlombok</gro

  • Slf4j+logback实现JSON格式日志输出方式

    目录 Slf4j+logback实现JSON格式日志输出 依赖 logback 记录JSON日志 Slf4j+logback实现JSON格式日志输出 依赖 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> <scope>provided</s

  • SpringMVC框架中使用Filter实现请求日志打印方式

    目录 查找资料后确定两种技术方案 1. 使用AOP对所有Controller的方法进行环绕通知处理: 2. 使用Filter拦截所有的Request和Response,并获取body. 最后选择了第二种方式,具体实现记录如下. 具体实现 日志记录过滤器 public class RequestFilter implements Filter{private static final String LOG_FORMATTER_IN = "请求路径:{%s},请求方法:{%s},参数:{%s},来源

  • SpringCloud Gateway之请求应答日志打印方式

    目录 Gateway请求应答日志打印 第一步 第二步 Gateway全局请求日志打印 把请求体的数据存入exchange 编写全局日志拦截器代码 在代码中配置全局拦截器 Gateway请求应答日志打印 请求应答日志时在日常开发调试问题的重要手段之一,那么如何基于Spring Cloud Gateway做呢,请看我上代码. 第一步 创建RecorderServerHttpRequestDecorator,缓存请求参数,解决body只能读一次问题. public class RecorderServ

  • Node.js中Koa2在控制台输出请求日志的方法示例

    前言 Koa2真的是个很轻量的框架,轻量到路由都作为了模块单独了出来,Koa2也没有日志功能,如果我们需要有一些请求的日志和时间,我们就需要引入日志中间件 下面话不多说了,来一起看看详细的介绍吧 引入时间格式化库MomentJS 安装MomentJS npm install moment --save 简单格式化时间 使用YYYY-MM-DD HH:MM:SS代表 年-月-日 时-分-秒(24小时制) console.log(Moment().format('YYYY-MM-DD HH:MM:S

  • log4j控制日志输出文件名称的两种方式小结

    目录 log4j控制日志输出文件名称 1. 第一种方式 2. 第二种方式(这种方式亲测正确) 如何随心所欲地自定义log4j输出格式 log4j控制日志输出文件名称 1. 第一种方式 在类对象中用如下方式定义logger变量 private static Logger logger = Logger.getLogger("lemmaXml"); 这样通过名称的方式获取logger,需要在log4j.properties文件中定义一个名称为lemmaXml的appender,配置如下:

  • Python日志:自定义输出字段 json格式输出方式

    最近有一个需求:将日志以json格式输出, 并且有些字段是logging模块没有的.看了很多源码和资料, 终于搞定, 抽取精华分享出来, 一起成长. import json import logging class JsonFilter(logging.Filter): ip = 'IP' source = 'APP' def filter(self, record): record.ip = self.ip record.username = self.source return True i

随机推荐