注解日志生成

//定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
    String value() default "";
}

SysLog切面:

/* @DESC:系统日志生成切面,将生成的日志保存到数据库中
 */
@Aspect
@Component
public class SysLogAspect {
    @Autowired
    private SysLogServiceInterface serviceInterface;
    private static final Logger LOGGER = LoggerFactory.getLogger(SysLogAspect.class);

    //Pointcut的名称 就是simplePointcut,此方法不能有返回值,该方法只是一个标示
    //用@annotation指定我们定义的注解
    @Pointcut("@annotation(com.orcl.frame.utils.annotation.SysLog)")
    public void logPointCut() {
    }
    SysLogModel sysLog = new SysLogModel();//日志实体类
     //JoinPoint我们所说的连接点,封装了SpringAop中切面方法的信息,在切面方法中添加JoinPoint参数,就可以获取到封装了该方法信息的JoinPoint对象
     @Before("logPointCut()")
    public void saveLog(JoinPoint joinPoint){
         try {
             MethodSignature signature = (MethodSignature) joinPoint.getSignature();
             Method method = signature.getMethod();
             SysLog syslog = method.getAnnotation(SysLog.class);
             if (null != syslog) {
                 //注解上的描述
                 sysLog.setOperation(syslog.value());
             }
             //请求的参数
             Object[] args = joinPoint.getArgs();
             String params = "";
             if (null != args && args.length > 0) {
                 params = JSON.toJSONString(args[0]);
             } else {
                 params = "no params";
             }
             sysLog.setParams(params);

             //请求的方法名
             String className = joinPoint.getTarget().getClass().getName();
             String methodName = signature.getName();
             sysLog.setMethod(className + "." + methodName + "()");

             //获取request
             HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
             String ip = IPUtils.getIpAddr(request);
             sysLog.setIp(ip);

             //获取操作用户
//         LoginRequest o = (LoginRequest)request.getSession().getAttribute("loginUser");//从seeion中获取登录对象
             String userName = "007";//当前登录的用户名
             sysLog.setUserName(userName);
             sysLog.setCreateDate(new Date());
//        serviceInterface.insert(sysLog);
         } catch (Throwable e) {
             LOGGER.error("发生异常是{}",e);
         }
    }
    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        LOGGER.info("RESPONSE : " + ret);
        String res = ret.toString();
        sysLog.setDescription(res);
        serviceInterface.insert(sysLog);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值