spring的aop实现日志记录

对于一个已经做好的系统,对某些业务实现日志记录,例如crud操作的类型,可以用spring 的aop取实现。具体实现如下:

我用的是注解版本的,首先要在配置文件中加配置,


 

然后,新建一个注解用来标志要记录日志的controller

@Target(value = { ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented 
public @interface SaveLogAnnotation {
	String operateDesc();
	OperateType operateType();//枚举
	PlatformType platformType();//枚举
}

切面类来进行具体的操作

    @Aspect
	@Component
	public class TxAop {
		@Autowired
		private  HttpServletRequest request;
		private static final String OPERATE_TYPE = "operateType";
		private static final String PLATFORM_TYPE = "platformType";
		//@Pointcut("execution(* org.roger.service.impl.*.*(..))")
		@Pointcut("@annotation(org.roger.test.SaveLogAnnotation)")
		public void pt(){}
		
		// 请求method前进行切面
		@Before(value = "operateLogAspect()")
		public void methodBefore(JoinPoint joinPoint){
			try {
				/*ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
						.getRequestAttributes();
				HttpServletRequest request = requestAttributes.getRequest();*/	
				String requestAddr=request.getRequestURL().toString();
				Map operateMap=getOperateType(joinPoint);
				String platformType=operateMap.get(PLATFORM_TYPE);
				
				logger.info("请求地址:" + requestAddr);
				logger.info("请求类方法:" + joinPoint.getSignature().toString());
				String requestParams=Arrays.toString(joinPoint.getArgs());
				logger.info("请求类方法参数:" + requestParams);
				logger.info("平台类型:" + platformType);
				logger.info("用户ip:" + NetworkUtil.getIpAddress(request));
				//保存操作日志入库
				AuditLogDto info=new AuditLogDto();
				info.setTransNo(LogTransNoUtil.getTransNo());
				info.setOperateBy(operateBy);
				info.setOperateDesc(operateMap.get(OPERATE_DESC));
				info.setOperateType(operateMap.get(OPERATE_TYPE));
				info.setRequestIp(NetworkUtil.getIpAddress(request));
				info.setRequestAddr(requestAddr);
				info.setRequestMethod(joinPoint.getSignature().toString());
				info.setRequestParams(requestParams);
				info.setPlatformType(platformType);
				auditLogService.saveAuditLog(info);
			} catch (Exception e) {
				logger.error("ERROR:", e);
			}
		}

		/**
		 * 获取操作类型
		 * @return 方法描述
		 * @throws Exception
		 */
		private Map getOperateType(JoinPoint joinPoint)throws Exception {
			Class targetClass = joinPoint.getTarget().getClass();
			Method[] methods = targetClass.getMethods();
			String methodName = joinPoint.getSignature().getName();
			for (Method method : methods) {
				if (method.getName().equals(methodName)) {
					Map result = new HashMap();
					result.put(OPERATE_DESC, method.getAnnotation(SaveLogAnnotation.class).operateDesc());
					result.put(OPERATE_TYPE, method.getAnnotation(SaveLogAnnotation.class).operateType().toString());
					result.put(PLATFORM_TYPE, method.getAnnotation(SaveLogAnnotation.class).platformType().toString());
					return result;
				}
			}
			return null;
		}
	}

获取ip地址工具类

public final class NetworkUtil {  
    /** 
     * Logger for this class 
     */  
	private static final Logger logger = LoggerFactory.getLogger(NetworkUtil.class);

  
    /** 
     * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址; 
     *  
     * @param request 
     * @return 
     * @throws IOException 
     */  
    public final static String getIpAddress(HttpServletRequest request) throws IOException {  
        // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址  
  
        String ip = request.getHeader("X-Forwarded-For");  
        if (logger.isInfoEnabled()) {  
            logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);  
        }  
  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("Proxy-Client-IP");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("WL-Proxy-Client-IP");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("HTTP_CLIENT_IP");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);  
                }  
            }  
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
                ip = request.getRemoteAddr();  
                if (logger.isInfoEnabled()) {  
                    logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);  
                }  
            }  
        } else if (ip.length() > 15) {  
            String[] ips = ip.split(",");  
            for (int index = 0; index < ips.length; index++) {  
                String strIp = (String) ips[index];  
                if (!("unknown".equalsIgnoreCase(strIp))) {  
                    ip = strIp;  
                    break;  
                }  
            }  
        }  
        return ip;  
    }  
} 

最后在controller的请求方法上加注解即可

@SaveLogAnnotation(operateDesc="操作描述",operateType=OperateType.ADD,platformType=PlatformType.APP)

你可能感兴趣的:(后端知识)