package com.imyeyu.spring.annotation; import com.imyeyu.java.TimiJava; import com.imyeyu.spring.TimiSpring; import com.imyeyu.spring.bean.PageResult; import com.imyeyu.spring.entity.IDEntity; import com.imyeyu.utils.Text; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * AOP 切面日志 * * @author 夜雨 * @version 2021-08-17 16:26 */ @Aspect @Component public class AOPLogInterceptor { /** 全局请求追踪 ID Key */ public static final String REQUEST_ID = "TIMI_SPRING_REQUEST_ID"; private static final Logger log = LoggerFactory.getLogger(AOPLogInterceptor.class); /** * 创建 AOP 日志拦截器 */ public AOPLogInterceptor() { } /** 注入注解 */ @Pointcut("@annotation(com.imyeyu.spring.annotation.AOPLog)") public void logPointCut() { } /** * 执行前 * * @param joinPoint 切入点 */ @Before("logPointCut()") public void doBefore(JoinPoint joinPoint) { String uuid = Text.tempUUID(); TimiSpring.setSessionAttr(REQUEST_ID, uuid); log.info("ID: {} Request -> IP: {}, URI: {}", uuid, TimiSpring.getRequestIP(), TimiSpring.getRequest().getRequestURI()); } /** * 执行后 * * @param response 返回内容 * @throws Throwable 异常 */ @AfterReturning(returning = "response", pointcut = "logPointCut()") public void doAfterReturning(Object response) throws Throwable { String msg = "ID: {} Response <- Return."; switch (response) { case IDEntity entity -> // 返回实体 msg += entity.getClass().getSimpleName() + "." + entity.getId(); case PageResult pageResult -> { // 返回数组 if (pageResult.getList().isEmpty()) { msg += "PageResult Empty"; } else { if (pageResult.getList().getFirst() == null) { msg += "PageResult." + pageResult.getList().size(); } else { msg += "PageResult<%s>[%s]".formatted(pageResult.getList().getFirst().getClass().getSimpleName(), pageResult.getList().size()); } } // 返回数据页 } case String string -> { // 返回字符串 if (string.length() < 64) { msg += string; } else { msg += string.substring(0, 64) + ".."; } msg = msg.replaceAll("[\\r\\n]+", ""); } case Boolean bool -> // 返回布尔值 msg += bool; case Number number -> // 返回数字 msg += response.getClass().getSimpleName() + ".[" + number.doubleValue() + "]"; case null, default -> { // 其他对象 if (TimiJava.isNotEmpty(response)) { msg += response.getClass().getSimpleName(); } else { msg += "NULL"; } } } log.info(msg, TimiSpring.getSessionAttr(REQUEST_ID)); } /** * 环绕 * * @param pjp 切入点 * @return 执行返回 * @throws Throwable 异常 */ @Around("logPointCut()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { return pjp.proceed(); } }