自定义注解实现日志管理

首先定义一个注解:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface LogAnnotation {
    //模块名
    Constant.LogModule moduleName() default Constant.LogModule.OTHER;
    //操作内容
    String operationContent() default "";
}

在方法上面添加注解:

@LogAnnotation(moduleName = Constant.LogModule.CERTIFICATEMGR, operationContent = "修改")
@RequestMapping(value = "/{certificateId}", method = RequestMethod.POST, produces = {"text/plain"})
public void updateCertificate(MultipartHttpServletRequest request, @PathVariable String certificateId) throws ParseException, IOException {
}

日志监听及记录:

@Aspect
@Component
public class OperaLog {

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @Resource
    AfcsOperationLogMapper operationLogMapper;

    @Resource
    AfcsUserMapper userMapper;

    @Autowired
    Context context;

    @Pointcut("@annotation(com.nikoyo.acs.LogAnnotation)")
    public void controllerAspect() {
    }

    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) {
        //handleLog(joinPoint, null);
    }

    @AfterReturning(pointcut="controllerAspect()",returning = "returnValue")
    public  void doAfter(JoinPoint joinPoint,Object returnValue) {
        handleLog(joinPoint,returnValue,null);
    }

    @AfterThrowing(value="controllerAspect()",throwing="e")
    public void doAfter(JoinPoint joinPoint, Exception e) {
        //handleLog(joinPoint, e);
    }

    private void handleLog(JoinPoint joinPoint,Object returnValue,Exception e) {
        //记录日志
        //例如:
        ----------
        try {
                 //获得注解
                 LogAnnotation logAnnotation = giveController(joinPoint);
                if(logAnnotation == null)
                 {
                     return;
                 }

                 Date date = new Date();
                 String requestUri = request.getRequestURI();
                 String id = UUID.randomUUID().toString();
                 String ipAddress = getClientIpAddr(request);//真实IP
                 String userId=context.getUserId();
                 String userName=null;
                 if(StringUtils.isNotEmpty(userId)){
                     userName=userMapper.selectByPrimaryKey(userId).getUserName();
                 }
                 String moduleName=logAnnotation.moduleName().getName();
                 String operationContent=logAnnotation.operationContent();

                 AfcsOperationLog operationlog = new AfcsOperationLog();
                 operationlog.setIp(ipAddress);
                 operationlog.setCreationDate(date);
                 operationlog.setLogId(id);
                 if(StringUtils.isNotEmpty(userId)){
                     operationlog.setUserId(userId);
                 }else {
                     operationlog.setUserId("Unknown");
                 }
                 operationlog.setUserName(userName);
                 operationlog.setModuleName(moduleName);
                 operationlog.setOperationContent(operationContent);
                 if(requestUri.length()>100){
                     int i=requestUri.lastIndexOf("/");
                     String re=requestUri.substring(0,i);
                     operationlog.setRequestUrl(re);
                 }else{
                     operationlog.setRequestUrl(requestUri);
                 }
                 if(returnValue instanceof String){
                     operationlog.setResult(returnValue.toString());
                 }
                 operationLogMapper.insertSelective(operationlog);
             } catch (Exception exp) {
                 //logger.error("异常信息:{}", exp.getMessage());
                 exp.printStackTrace();
             }

        ----------


    }

    private static LogAnnotation giveController(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(LogAnnotation.class);
        }
        return null;
    }

    /***
     * 获取客户端ip地址(可以穿透代理)
     * @param request
     * @return
     */
    public static String getClientIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_VIA");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("REMOTE_ADDR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值