对于监控日志,就是把各个需要监控的函数的操作存入数据库,供需要的时候,做查询展示。可能很多个方法都要做监控,而动作又都一样,无非就是把请求参数,返回结果,操作人,操作时间,ip来源等信息放入数据库保存。这种场景就适合在切面处理,只要在需要监控的各个方法上加切点即可。

切点的概念即aop的基础知识不再赘述。

直接贴代码

1,切点位置

@SysLog("催计-发短信")
@RequestMapping(value = "/doMessage.do")
@ResponseBody
public Map<String, Object> doMessage(HttpServletRequest request) throws Exception {}

@SysLog("催计-发短信")这个注解就是该方法的切点,就是要对doMessage这个方法做监控日志。

2,自定义注解
package com.fh.annotation;
/**
* 系统日志注解
*
* @author xuxiaorong
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {

String value() default "";
}
此处, String value() default "";就是说@SysLog("催计-发短信")注解的值为String 类型
@Target(ElementType.METHOD)是定义该注解作用在方法上

3,切面处理类
/**
* 系统日志,切面处理类
*
* @author xuxiaorong
*/
@Aspect 此处是声明这个类为一个切面
@Component 此处是把这个切面类交给spring容器
public class SysLogAspect {
Logger logger = LoggerFactory.getLogger(SysLogAspect.class);

@Autowired
private OperatorLogMapper logService;

@Pointcut("@annotation(com.fh.annotation.SysLog)")
public void logPointCut() {

}
此处 是声明是哪个切点,监控日志我们是用@SysLog,该注解的类路径为com.fh.annotation.SysLog
   public void logPointCut() {

}

@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//获取签名
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
//请求的方法名
String className = point.getTarget().getClass().getName();
String methodName = signature.getName();
SysLog syslogAnnotation = method.getAnnotation(SysLog.class);
Object result = null;
//操作记录 参数+数据
StringBuilder info = new StringBuilder();
Integer status = new Integer(0);
//设置IP地址 操作人+Ip
String ip = "";
try {
//系统注销时获取
ip = before();
//执行方法
result = point.proceed();
try {
info.append("参数:")
.append(getParam(JSON.toJSONString(((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest().getParameterMap()),syslogAnnotation.value()))
.append(";返回值:")
.append(result == null ? "" : (String) JsonUtil.toJsonString(result));
if (result instanceof ResultJSON &&JSON.toJSONString(result).contains("false")) {
status = 1;
}
} catch (Exception ex) {
logger.error("转json异常", ex);
info.setLength(0);
info.append( "异常:转json异常");
status = 1;
}
//系统登陆是获取
ip = after(ip);
} catch (Throwable ex) {//异常通知
logger.error(className + "." + methodName + "():执行异常" + ex.getMessage(), ex);
info.setLength(0);
info.append("异常:" + JSON.toJSONString(ex.getStackTrace()[0]));
status = 1;
}
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
logger.info("操作日志信息{" + className + "." + methodName
+ "():执行" + syslogAnnotation.value() + "耗时" + "" + time + "毫秒}");
//保存日志
saveSysLog(syslogAnnotation.value(), status, info, ip, result, time);

return result;
}


 

posted on 2017-10-19 13:41  xue123  阅读(33)  评论(0编辑  收藏  举报