March21Sunny - AOP
type: channel
link: https://jianz.xyz/index.php/tag/AOP/
items: SpringBoot | AOP切面日志记录

SpringBoot | AOP切面日志记录
type: item
date: 2021-11-13T02:47:00+00:00
description: SysLog 注解import java.lang.annotation.*; @Target(ElementType.METHOD) //该注解应用于方法 @Retention(RetentionPolicy.RUNTIME) //在vm运行期间保留注解 @Documented //将注解包含在javadoc中 public @interface SysLog { String value() default ""; // 接口名称 boolean check() default true; //是否校验token }切面处理类 /** * 系统日志，切面处理类 * 处理@SysLog注解 */ @Aspect @Component public class SysLogAspect { private static Logger logger = LoggerFactory.getLogger(SysLogAspect.class); @Autowired private SysLogMapper sysLogMapper; /** * SpringBoot获取当前环境代码,Spring获取当前环境代码 */ @Value("${spring.profiles.active}") private String profiles; @Pointcut("@annotation(com.zhang.oneday.common.annotation.SysLog)") public void logPointCut() { } @Around("logPointCut()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { long beginTime = System.currentTimeMillis(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLogEntity sysLog = new SysLogEntity(); SysLog syslog = method.getAnnotation(SysLog.class); if (syslog != null) { //注解上的描述 String value = syslog.value(); logger.info("=====> {}", value); sysLog.setOperation(value); } HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); //请求的方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); sysLog.setIp(IPUtils.getIp(request)); sysLog.setCreateDate(new Date()); sysLog.setProfiles(profiles); //请求的参数 Object[] args = joinPoint.getArgs(); JSONObject paramObj = new JSONObject(); Map<String, String[]> paramMap = request.getParameterMap(); for (String key : paramMap.keySet()) { String[] values = paramMap.get(key); for (int i = 0; i < values.length; i++) { String value = values[i]; paramObj.put(key, value); } } String params = paramObj.isEmpty() ? "" : JSONObject.toJSONString(paramObj); sysLog.setParams(params); logger.info("==> 参数：{}", params); // token验证（拦截…