1. 程式人生 > >自定義註解實現日誌管理

自定義註解實現日誌管理

首先定義一個註解:

@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; } }