自定义注解实现日志管理

来源:互联网 发布:织带打版软件 编辑:程序博客网 时间:2024/05/22 19:57

首先定义一个注解:

@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD})@Documentedpublic @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@Componentpublic 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 0
原创粉丝点击