您的位置:首页 > 编程语言 > Java开发

Spring boot 使用AOP统一处理日志

2018-07-05 17:59 169 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/litao_777/article/details/80930298

在 Spring boot里配置AOP其实很简单,只需在pom文件里加入

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
然后配置切面类,下面是配置了一个环绕通知
@Aspect
@Component
public class LoggerInterceptor {

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Around("within(com..*) && @annotation(log)")
public Object doAroundMethod(ProceedingJoinPoint pjd, Log log) throws Throwable {

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request =  attributes.getRequest();
//路径
logger.info("方法路径:{}",pjd.getSignature().getDeclaringTypeName()+'.'+ pjd.getSignature().getName());//获取类名及类方法
//ip
logger.info("调用ip:{}",request.getRemoteAddr());
//定义的注解
String name = log.name();//操作方法名
logger.info("操作方法名:{}", name);
Object[] params = pjd.getArgs();//获取请求参数
logger.info("监听到传入参数为:{}",JSON.toJSONString(params));
//###################上面代码为方法执行前#####################
Object result  = pjd.proceed();//执行方法,获取返回参数
//###################下面代码为方法执行后#####################
logger.info("返回参数为:{}",JSON.toJSONString(result));
return result;

}
}
上面环绕通知的触发条件为com.包下并且打了自定义注解log通知才会织入,下面是自定义注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
/**
* 接口名字
* @return
*/
String name() default "";
}

例子

目标方法未加注解/** * 验证验证码 * @param phone 手机号 * @param code 验证码 */ //@Log(name = "验证验证码") public Boolean verification(String phone,String code){ // -----------------String类型数据操作 start-------------------- String s=redisTemplate.opsForValue().get("wallet"+phone); boolean b = code.equals(s); return b; }test@Test public void testAop() { verificationCode.verification("15090009000", "954385"); }结果

添加注解后结果为

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