『博客开发日记』之通过AOP实现日志记录功能

本文最后更新于 2026年2月8日 下午

通过AOP实现日志记录功能


日志记录功能

需要通过日志记录接口调用信息 便于后期调试排查

可能有很多接口都需要进行日志的记录

相当于是对原有的功能进行增强 并且是批量的增强

代码实现

自定义注解类


日志打印类


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//日志打印切面类
@Component
@Aspect
@Slf4j
public class LogAspect
{
//切点
@Pointcut("@annotation(com.mengze.annotation.SystemLog)")
public void pt() {

}

//通知方法(环绕通知)
@Around("pt()")
public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable
{
Object ret;
try {
handleBefore(joinPoint);
ret = joinPoint.proceed();
handleAfter(ret);
} finally {
// 结束后换行
log.info("=======End=======" + System.lineSeparator());//系统换行符(适配win/linux)


}

return ret;

}

private void handleAfter(Object ret) {
// 打印出参
log.info("Response : {}", JSON.toJSONString(ret));
}

private void handleBefore(ProceedingJoinPoint joinPoint) {

ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();

//获取被增强方法上的注解对象
SystemLog systemLog = getSystemLog(joinPoint);

log.info("=======Start=======");
// 打印请求 URL
log.info("URL : {}", request.getRequestURL());
// 打印描述信息
log.info("BusinessName : {}", systemLog.businessName());
// 打印 Http method
log.info("HTTP Method : {}", request.getMethod());
// 打印调用 controller 的全路径以及执行方法
log.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
// 打印请求的 IP
log.info("IP : {}", request.getRemoteHost());
// 打印请求入参
log.info("Request Args : {}", JSON.toJSONString(joinPoint.getArgs()));

}

private SystemLog getSystemLog(ProceedingJoinPoint joinPoint)
{
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
SystemLog systemLog = methodSignature.getMethod().getAnnotation(SystemLog.class);
return systemLog;
}
}

运行后控制台输出日志



PS:该系列只做为作者学习开发项目做的笔记用

不一定符合读者来学习,仅供参考


预告

后续会记录博客的开发过程

每次学习会做一份笔记来进行发表

“一花一世界,一叶一菩提”


版权所有 © 2025 云梦泽
欢迎访问我的个人网站:https://hgt12.github.io/


『博客开发日记』之通过AOP实现日志记录功能
http://example.com/2026/02/08/『博客开发日记』之通过AOP实现日志记录功能/
作者
云梦泽
发布于
2026年2月8日
更新于
2026年2月8日
许可协议