You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Netty访问日志中排除/health API请求

排除Netty访问日志中的/actuator/health请求

有两种实用方法可以实现需求,分别从Reactor Netty底层配置和日志框架过滤两个方向入手:

方法一:自定义Reactor Netty访问日志工厂

通过实现AccessLogFactory接口,在日志生成前判断请求路径,跳过指定接口的日志输出。

  1. 实现自定义AccessLogFactory:
import reactor.netty.http.server.AccessLog;
import reactor.netty.http.server.AccessLogFactory;
import reactor.netty.http.server.HttpServerRequest;
import reactor.netty.http.server.HttpServerResponse;

public class ExcludeHealthAccessLogFactory implements AccessLogFactory {
    private final AccessLogFactory defaultFactory = AccessLogFactory.DEFAULT;
    private static final String EXCLUDED_HEALTH_PATH = "/actuator/health";

    @Override
    public AccessLog create(HttpServerRequest request, HttpServerResponse response) {
        if (EXCLUDED_HEALTH_PATH.equals(request.uri())) {
            // 返回空实现,不生成该路径的日志
            return () -> {};
        }
        // 其他请求沿用默认日志逻辑
        return defaultFactory.create(request, response);
    }
}
  1. 在Spring Boot中配置Netty服务器自定义器,替换默认日志工厂:
import org.springframework.boot.web.embedded.netty.NettyServerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.netty.http.server.HttpServer;

@Configuration
public class NettyAccessLogConfig {
    @Bean
    public NettyServerCustomizer accessLogCustomizer() {
        return httpServer -> httpServer
                // 启用访问日志并绑定自定义工厂
                .accessLog(true, new ExcludeHealthAccessLogFactory());
    }
}

注意:配置后请移除原来的System.setProperty("reactor.netty.http.server.accessLogEnabled", "true"),因为accessLog(true, factory)会覆盖系统属性的配置。

方法二:通过日志框架过滤(以Logback为例)

如果不想修改代码,可直接在日志配置中过滤掉包含/actuator/health的访问日志条目。

在logback.xml中添加过滤器配置:

<configuration>
    <!-- 其他基础配置 -->

    <!-- 定义访问日志输出Appender,添加路径过滤规则 -->
    <appender name="ACCESS_LOG_FILE" class="ch.qos.logback.core.FileAppender">
        <file>${LOG_PATH}/access.log</file>
        <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
            <evaluator>
                <expression>message.contains("/actuator/health")</expression>
            </evaluator>
            <OnMatch>DENY</OnMatch>
            <OnMismatch>ACCEPT</OnMismatch>
        </filter>
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>

    <!-- 绑定Reactor Netty访问日志的Logger -->
    <logger name="reactor.netty.http.server.AccessLog" level="INFO" additivity="false">
        <appender-ref ref="ACCESS_LOG_FILE"/>
    </logger>
</configuration>

这种方式无需修改业务代码,通过日志规则直接过滤,适合快速生效的场景。


内容的提问来源于stack exchange,提问作者bombo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 10:46:03