SpringBoot全局异常处理与日志记录的统一规范实战
更新时间:2026年07月08日 09:11:23 作者:张老师技术栈
线上系统出问题不可怕,可怕的是出了问题找不到原因,统一的异常处理和规范的日志记录是任何生产系统必备的基础设施,本文教你用全局异常处理+统一日志记录,快速定位线上Bug,掌握自定义异常、拦截器配置和日志级别调优,彻底告别排查难题,需要的朋友可以参考下
线上系统出问题不可怕,可怕的是出了问题找不到原因。统一的异常处理和规范的日志记录是任何生产系统必备的基础设施。
一、全局异常处理
1. 自定义业务异常
public class BusinessException extends RuntimeException {
private int code;
private String message;
public BusinessException(int code, String message) {
super(message);
this.code = code;
this.message = message;
}
// 常用错误码
public static BusinessException notFound(String msg) {
return new BusinessException(404, msg);
}
public static BusinessException badRequest(String msg) {
return new BusinessException(400, msg);
}
public static BusinessException unauthorized(String msg) {
return new BusinessException(401, msg);
}
public static BusinessException forbidden(String msg) {
return new BusinessException(403, msg);
}
}
2. 全局异常处理器
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(BusinessException.class)
public ResultVO<?> handleBusiness(BusinessException e) {
log.warn("业务异常: code={}, msg={}", e.getCode(), e.getMessage());
return ResultVO.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResultVO<?> handleValidation(MethodArgumentNotValidException e) {
String msg = e.getBindingResult().getFieldErrors().stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.joining(";"));
return ResultVO.error(400, msg);
}
@ExceptionHandler(ConstraintViolationException.class)
public ResultVO<?> handleConstraint(ConstraintViolationException e) {
String msg = e.getConstraintViolations().stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.joining(";"));
return ResultVO.error(400, msg);
}
@ExceptionHandler(NoHandlerFoundException.class)
public ResultVO<?> handle404(NoHandlerFoundException e) {
return ResultVO.error(404, "接口不存在: " + e.getRequestURL());
}
@ExceptionHandler(Exception.class)
public ResultVO<?> handleOther(Exception e) {
log.error("系统异常", e);
return ResultVO.error(500, "服务器繁忙,请稍后重试");
}
}
二、统一日志记录
1. 请求日志拦截器
@Component
public class LogInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(LogInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) {
// 记录请求开始时间
request.setAttribute("startTime", System.currentTimeMillis());
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
long start = (long) request.getAttribute("startTime");
long duration = System.currentTimeMillis() - start;
log.info("[{}] {} {} → {} ({}ms)",
request.getMethod(),
request.getRequestURI(),
request.getQueryString() != null ? "?" + request.getQueryString() : "",
response.getStatus(),
duration
);
}
}
2. 注册拦截器
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LogInterceptor logInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(logInterceptor)
.addPathPatterns("/api/**");
}
}
3. 日志级别配置
logging:
level:
root: INFO
com.zhang: DEBUG
com.zhang.seckill.mapper: TRACE
file:
path: /var/log/app
name: ${logging.file.path}/app.log
logback:
rolling policy:
max-history: 30
max-file-size: 100MB三、日志最佳实践
// ✅ 正确:带参数占位符
log.info("用户 {} 创建订单 {}", userId, orderNo);
// ❌ 错误:字符串拼接
log.info("用户 " + userId + " 创建订单 " + orderNo);
// ✅ 正确:包含上下文信息
log.warn("支付失败: orderNo={}, amount={}, error={}", orderNo, amount, error);
// ❌ 错误:没信息量的日志
log.info("支付失败");
到此这篇关于SpringBoot全局异常处理与日志记录的统一规范实战的文章就介绍到这了,更多相关SpringBoot全局异常处理与日志记录统一规范内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
mybatis条件构造器(EntityWrapper)的使用方式
这篇文章主要介绍了mybatis条件构造器(EntityWrapper)的使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-03-03


最新评论