Spring Boot中统一记录请求、响应及异常日志的方法

Spring Boot中统一记录请求、响应及异常日志的方法

技术背景

在开发基于Spring Boot的REST API时,为了便于调试、监控和问题排查,需要对所有请求和响应进行详细的日志记录,包括请求的输入参数、请求路径、查询字符串、对应的类方法,以及响应结果(包括成功和错误情况)。

实现步骤

1. 使用Spring Boot Actuator

Actuator是Spring Boot的一个模块,它提供了HTTP请求日志记录功能。

  • 添加依赖:在pom.xml中添加spring-boot-starter-actuator依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  • 配置端点:在application.properties中配置要暴露的端点。
management.endpoints.web.exposure.include=*
  • 查看日志:启动应用后,可以通过访问/actuator/httptrace查看最近的100个HTTP请求。

2. 使用CommonsRequestLoggingFilter

Spring提供了CommonsRequestLoggingFilter来记录请求日志。

  • 配置过滤器:在配置类中添加过滤器Bean。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CommonsRequestLoggingFilter;

@Configuration
public class LoggingConfig {
   

    @Bean
    public CommonsRequestLoggingFilter requestLoggingFilter() {
   
        CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
        loggingFilter.setIncludeClientInfo(true);
        loggingFilter.setIncludeQueryString(true);
        loggingFilter.setIncludePayload(true);
        loggingFilter.setMaxPayloadLength(64000);
        return loggingFilter;
    }
}
  • 设置日志级别:在application.properties中设置过滤器的日志级别为DEBUG
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG

3. 自定义DispatcherServlet

通过自定义DispatcherServlet可以同时记录请求和响应日志。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1010n111

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值