本篇我们采用自定义注解+AOP切面编程技术,实现快捷高效的日志记录。
在项目进行中我们在日志记录的过程中,发现一种日志记录方式为 AOP+自定义注解+工具类的实现方式。
这到底是什么原理?这种方式究竟有什么用途?
1、传统的日志用法
1.1、实现展示
我们来看看传统的日志用法,我们将日志记录的行为放在Service方法的逻辑中,通过调用LogUtils工具类中的方法(LogUtils工具类代码省略),对日志进行输出:
1 2 3 4 5 6
| @Override public Result findArticleById(Long articleId) { LogUtils.addLog("文章" , "获取文章列表"); return Result.success(articleVo); }
|
1.2、存在问题
这个方式还是有一定的问题:
日志记录代码与业务代码强耦合:我们此时在LogUtils.addLog()
方法中定义了两个参数,可如果有一天我们想在这个方法中再加入一个参数,那么我们就要修改底层工具类+所有调用的地方进行修改,这是因为方法的调用不能缺少参数。
2、进化后的日志用法
2.1、实现展示
我们采用 自定义注解+AOP切面编程技术,实现日志记录,现在记录日志的方式就是这样了
1 2 3 4 5 6
| @LogAnnotation(module = "文章",operation = "获取文章列表") @Override public Result findArticleById(Long articleId) { return Result.success(articleVo); }
|
2.2、此方法的优点
- 使用注解于方法上面很方便
- 对于参数的添加和修改很方便(可以直接在自定义注解中进行参数修改)
- 在我们添加了参数之后,我们不用修改注解的调用(因为我们在注解的定义添加了默认值)
3、代码实现
我们定义一个注解加载业务代码方法上,使用AOP查找注解的调用,并对其方法进行逻辑增强
3.1、自定义注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface LogAnnotation {
String module() default ""; String operation() default ""; }
|
3.2、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
|
@Aspect @Component @Slf4j public class LogAspect {
@Pointcut("@annotation(com.blog.common.aop.LogAnnotation)") public void logPointCut() { }
@Around("logPointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { long beginTime = System.currentTimeMillis(); Object result = point.proceed(); long time = System.currentTimeMillis() - beginTime; recordLog(point, time); return result; }
private void recordLog(ProceedingJoinPoint joinPoint, long time) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class); log.info("=====================log start================================"); log.info("module:{}",logAnnotation.module()); log.info("operation:{}",logAnnotation.operation());
String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); log.info("request method:{}",className + "." + methodName + "()");
Object[] args = joinPoint.getArgs(); String params = JSON.toJSONString(args[0]); log.info("params:{}",params);
HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); log.info("ip:{}", IpUtils.getIpAddr(request));
log.info("excute time : {} ms",time); log.info("=====================log end================================"); } }
|
3.3、Http工具类
1 2 3 4 5 6 7 8 9
|
public class HttpContextUtils { public static HttpServletRequest getHttpServletRequest(){ return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } }
|
3.4、IpUtils工具类
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
|
public class IpUtils {
private static Logger logger = LoggerFactory.getLogger(IpUtils.class);
public static String getIpAddr(HttpServletRequest request) { String ip = null; try { ip = request.getHeader("x-forwarded-for"); if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } catch (Exception e) { logger.error("IPUtils ERROR ", e); } if (StringUtils.isEmpty(ip) && ip.length() > 15) { if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } return ip; } }
|
至此SpringBoot+AOP+Annotation的日志输出功能实现完成。