1. Custom annotations
/** * System log comments * * @author chenshun * @email [email protected] *@date March 8, 2017 at 10:19:56 AM */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SysLog { String value() default ""; }
Second, cut surface processing
/** * System log, aspect processing class */ @Aspect @Component public class SysLogAspect { @Autowired private SysLogService sysLogService; @Pointcut("@annotation(io.renren.common.annotation.SysLog)") public void logPointCut() { } @Around( "logPointCut()" ) public Object around(ProceedingJoinPoint point) throws Throwable { long beginTime = System.currentTimeMillis(); // Execution method Object result = point.proceed(); // Execution duration (milliseconds) long time = System.currentTimeMillis() - beginTime; // Save the log saveSysLog(point, time); return result; } private void saveSysLog(ProceedingJoinPoint joinPoint, long time) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLogEntity sysLog = new SysLogEntity(); SysLog syslog = method.getAnnotation(SysLog.class ); if (syslog != null ){ // Description on the annotation sysLog.setOperation( syslog.value ()); } // Request method name String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); // Requested parameters Object[] args = joinPoint.getArgs(); try { String params = new Gson().toJson(args[0]); sysLog.setParams(params); }catch (Exception e){ } //获取request HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); //设置IP地址 sysLog.setIp(IPUtils.getIpAddr(request)); //用户名 String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername(); sysLog.setUsername(username); sysLog.setTime(time); sysLog.setCreateDate( new Date()); // Save system log sysLogService.save(sysLog); } }