您的位置:首页 > 运维架构

AOP实现用户操作日志记录

2017-10-16 14:55 513 查看

一、自定义注解

在使用aop切面拦截的时候需要统一的日志描述,这个日志描述,我们使用自定义注解来为每个方法添加日志自定义描述内容。

创建一个自定义注解类

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UserLogAnnotation {
String module()  default "";
String methods()  default "";
}


SpringMvc配置aop

SpringMvc.xm增加以下代码

xmlns:aop="http://www.springframework.org/schema/aop" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd

<aop:aspectj-autoproxy proxy-target-class="true" />
<!-- aop的执行类 -->
<bean id="userLogAopAction" class="com.topwalk.bdp.log.web.UserLogAopAction"/>


AOP拦截执行类

@Aspect
public class UserLogAopAction extends WebController {

@Autowired
private UserLogService userLogService;

@Pointcut("execution(* com.topwalk.icgap.*.web..*.*(..))")
private void controllerAspect() {}// 定义一个切入点

@Around("controllerAspect()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {

// 创建日志实体对象
UserLog log = new UserLog();

// 获取当前登录用户
User userInfo = HttpUtil.getSessionUser();
// 设置用户信息
log.setAccount(userInfo.getAccount());
log.setUserId(userInfo.getId());
log.setUserName(userInfo.getName());
log.setOrgCode(userInfo.getOrgCode());
log.setOrgName(userInfo.getOrgName());
// 当前IP地址
String theIp = HttpUtil.getIpAddr();
log.setIp(theIp);

// 获取当前拦截的实体类
/*Object target = pjp.getTarget();*/
// 拦截的方法参数类型
Signature sig = pjp.getSignature();

MethodSignature methodSignature = (MethodSignature) sig;

Object object = null;
Method method = null;
try {
/* method = target.getClass().getMethod(methodName, parameterTypes); */
method = methodSignature.getMethod();
} catch (SecurityException e1) {
e1.printStackTrace();
}

if (null != method) {
// 判断是否包含自定义的注解
if (method.isAnnotationPresent(UserLogAnnotation.class)) {
UserLogAnnotation userLogAnnotation =  method
.getAnnotation(UserLogAnnotation.class);
String module = userLogAnnotation.module();
String methods = userLogAnnotation.methods();

try {
//拼接描述信息
String description = "[帐号:"+log.getAccount()+"],"+"操作"+module+"模块,"+"执行"+methods;
log.setDescription(description);
log.setModule(Module.OTHER);
log.setFunction(Function.OTHER);
super.info(log);

object = pjp.proceed();
} catch (Exception e) {
e.printStackTrace();
}

} else {// 没有包含注解
object = pjp.proceed();
}
} else { // 不需要拦截直接执行
object = pjp.proceed();
}
return object;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  aop