详解Spring Boot中使用AOP统一处理Web请求日志
作者:zmken497300 发布时间:2021-08-24 15:50:17
标签:spring,boot,aop,日志
在spring boot中,简单几步,使用spring AOP实现一个 * :
1、引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、创建 * 类(在该类中,定义了拦截规则:拦截com.xjj.web.controller包下面的所有类中,有@RequestMapping注解的方法。):
/**
* * :记录用户操作日志,检查用户是否登录……
* @author XuJijun
*/
@Aspect
@Component
public class ControllerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);
@Value(“${spring.profiles}”)
private String env;
/**
* 定义拦截规则:拦截com.xjj.web.controller包下面的所有类中,有@RequestMapping注解的方法。
*/
@Pointcut(“execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)”)
public void controllerMethodPointcut(){}
/**
* * 具体实现
* @param pjp
* @return JsonResult(被拦截方法的执行结果,或需要登录的错误提示。)
*/
@Around(“controllerMethodPointcut()”) //指定 * 规则;也可以直接把“execution(* com.xjj………)”写进这里
public Object Interceptor(ProceedingJoinPoint pjp){
long beginTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod(); //获取被拦截的方法
String methodName = method.getName(); //获取被拦截的方法名
Set<Object> allParams = new LinkedHashSet<>(); //保存所有请求参数,用于输出到日志中
logger.info(”请求开始,方法:{}”, methodName);
Object result = null;
Object[] args = pjp.getArgs();
for(Object arg : args){
//logger.debug(“arg: {}”, arg);
if (arg instanceof Map<?, ?>) {
//提取方法中的MAP参数,用于记录进日志中
@SuppressWarnings(“unchecked”)
Map<String, Object> map = (Map<String, Object>) arg;
allParams.add(map);
}else if(arg instanceof HttpServletRequest){
HttpServletRequest request = (HttpServletRequest) arg;
if(isLoginRequired(method)){
if(!isLogin(request)){
result = new JsonResult(ResultCode.NOT_LOGIN, “该操作需要登录!去登录吗?\n\n(不知道登录账号?请联系老许。)”, null);
}
}
//获取query string 或 posted form data参数
Map<String, String[]> paramMap = request.getParameterMap();
if(paramMap!=null && paramMap.size()>0){
allParams.add(paramMap);
}
}else if(arg instanceof HttpServletResponse){
//do nothing…
}else{
//allParams.add(arg);
}
}
try {
if(result == null){
// 一切正常的情况下,继续执行被拦截的方法
result = pjp.proceed();
}
} catch (Throwable e) {
logger.info(”exception: ”, e);
result = new JsonResult(ResultCode.EXCEPTION, “发生异常:”+e.getMessage());
}
if(result instanceof JsonResult){
long costMs = System.currentTimeMillis() - beginTime;
logger.info(”{}请求结束,耗时:{}ms”, methodName, costMs);
}
return result;
}
/**
* 判断一个方法是否需要登录
* @param method
* @return
*/
private boolean isLoginRequired(Method method){
if(!env.equals(“prod”)){ //只有生产环境才需要登录
return false;
}
boolean result = true;
if(method.isAnnotationPresent(Permission.class)){
result = method.getAnnotation(Permission.class).loginReqired();
}
return result;
}
//判断是否已经登录
private boolean isLogin(HttpServletRequest request) {
return true;
/*String token = XWebUtils.getCookieByName(request, WebConstants.CookieName.AdminToken);
if(“1”.equals(redisOperator.get(RedisConstants.Prefix.ADMIN_TOKEN+token))){
return true;
}else {
return false;
}*/
}
}
/**
* * :记录用户操作日志,检查用户是否登录……
* @author XuJijun
*/
@Aspect
@Component
public class ControllerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);
@Value("${spring.profiles}")
private String env;
/**
* 定义拦截规则:拦截com.xjj.web.controller包下面的所有类中,有@RequestMapping注解的方法。
*/
@Pointcut("execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void controllerMethodPointcut(){}
/**
* * 具体实现
* @param pjp
* @return JsonResult(被拦截方法的执行结果,或需要登录的错误提示。)
*/
@Around("controllerMethodPointcut()") //指定 * 规则;也可以直接把“execution(* com.xjj.........)”写进这里
public Object Interceptor(ProceedingJoinPoint pjp){
long beginTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod(); //获取被拦截的方法
String methodName = method.getName(); //获取被拦截的方法名
Set<Object> allParams = new LinkedHashSet<>(); //保存所有请求参数,用于输出到日志中
logger.info("请求开始,方法:{}", methodName);
Object result = null;
Object[] args = pjp.getArgs();
for(Object arg : args){
//logger.debug("arg: {}", arg);
if (arg instanceof Map<?, ?>) {
//提取方法中的MAP参数,用于记录进日志中
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) arg;
allParams.add(map);
}else if(arg instanceof HttpServletRequest){
HttpServletRequest request = (HttpServletRequest) arg;
if(isLoginRequired(method)){
if(!isLogin(request)){
result = new JsonResult(ResultCode.NOT_LOGIN, "该操作需要登录!去登录吗?\n\n(不知道登录账号?请联系老许。)", null);
}
}
//获取query string 或 posted form data参数
Map<String, String[]> paramMap = request.getParameterMap();
if(paramMap!=null && paramMap.size()>0){
allParams.add(paramMap);
}
}else if(arg instanceof HttpServletResponse){
//do nothing...
}else{
//allParams.add(arg);
}
}
try {
if(result == null){
// 一切正常的情况下,继续执行被拦截的方法
result = pjp.proceed();
}
} catch (Throwable e) {
logger.info("exception: ", e);
result = new JsonResult(ResultCode.EXCEPTION, "发生异常:"+e.getMessage());
}
if(result instanceof JsonResult){
long costMs = System.currentTimeMillis() - beginTime;
logger.info("{}请求结束,耗时:{}ms", methodName, costMs);
}
return result;
}
/**
* 判断一个方法是否需要登录
* @param method
* @return
*/
private boolean isLoginRequired(Method method){
if(!env.equals("prod")){ //只有生产环境才需要登录
return false;
}
boolean result = true;
if(method.isAnnotationPresent(Permission.class)){
result = method.getAnnotation(Permission.class).loginReqired();
}
return result;
}
//判断是否已经登录
private boolean isLogin(HttpServletRequest request) {
return true;
/*String token = XWebUtils.getCookieByName(request, WebConstants.CookieName.AdminToken);
if("1".equals(redisOperator.get(RedisConstants.Prefix.ADMIN_TOKEN+token))){
return true;
}else {
return false;
}*/
}
}
3、测试
浏览器中输入:http://localhost:8082/api/admin/login
测试结果:
2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - 请求开始,方法:login
2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login请求结束,耗时:8ms
2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - 请求开始,方法:login
2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login请求结束,耗时:8ms
证明 * 已经生效。
源代码参考:https://github.com/xujijun/my-spring-boot
来源:http://blog.csdn.net/zmken497300/article/details/53516764


猜你喜欢
- Java集合删除元素ArrayList实例详解AbstractCollection集合类中有一个remove方法,该方法为了适配多种不同的集
- Android有三个基础组件Activity,Service和BroadcastReceiver,他们都是依赖Intent来启动。本文介绍的
- 前言Jetpack Compose(简称 Compose )是 Google 官方推出的基于 Kotlin 语言的 Android 新一代
- 栈和队列:都是线性表,都是基于List基础上的实现线性表:数组,链表,字符串,栈,队列元素按照一条“直线&rdq
- 使用正则抓捕网上邮箱这就是我们需要抓捕的网站。实现思路:1、使用java.net.URL对象,绑定网络上某一个网页的地址2、通过java.n
- SpringBoot运行Test时报错运行Test时的报错信息:SpringBoot Unable to find a @SpringBoo
- //Main:using System;using System.Collections.Generic;using System.Linq
- Dotnet中嵌入资源(位图、图标或光标等)有两种方式,一是直接把资源文件加入到项目,作为嵌入资源,在代码中通过Assembly的GetMa
- volatile先看个例子class Test {// 定义一个全局变量 private boolean isRu
- 知识点回顾封装封装(有时称为数据隐藏)是与对象有关的一个重要概念。从形式上来看,封装不过是将数据和行为组合在一个包中,并对对象的使用者隐藏了
- Web UI项目中, 很多 Spring controller 视图函数直接返回 html 页面, 还有一些视图函数是要重定向或转发到其他的
- Android自定义View仿探探卡片滑动这种效果网上有很多人已经讲解了实现思路,大多都用的是RecyclerView来实现的,但是我们今天
- Android中图片的左右切换随处可见,今天我也试着查阅资料试着做了一下,挺简单的一个小Demo,却也发现了一些问题,话不多说,上代码~:使
- 本文介绍spring中自定义缓存resolver,通过自定义resolver,可以在spring的cache注解中增加附加处理。一、概述ca
- java并发之ArrayBlockingQueue详细介绍 ArrayBlockingQueue是常用的线程集合,在线程池中也常常
- 本文为大家分享了C# 7.0中的解构功能,供大家参考,具体内容如下解构元组C#7.0新增了诸多功能,其中有一项是新元组(ValueTuple
- 什么是 MyBatis ?MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有
- 本文实例讲述了C#中Params的用法。分享给大家供大家参考。具体方法如下:using System;namespace Params{&n
- 微信支付现在已经变得越来越流行了,随之也出现了很多以可以快速接入微信支付为噱头的产品,不过方便之余也使得我们做东西慢慢依赖第三方,丧失了独立
- 1、什么是委托从数据结构来讲,委托是和类一样是一种用户自定义类型。委托是方法的抽象,它存储的就是一系列具有相同签名和返回回类型的方法的地址。