springboot中对请求的信息进行记录,使用aop切面方式来实现,直接上代码:
引入依赖
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- userAgent 解析 -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>
实现类
/**
* @Auther: yuanzhi
* @Date: 2019-4-23 13:57
* @Description: 使用aop实现请求日志的记录
*/
@Aspect
@Component
@Slf4j
public class AopLogRecord {
private static final String START_TIME = "request-start-time";
/**
* 切入点
* 此项目根据需求屏蔽了External开头的Controller
*/
@Pointcut("!execution(public * com.lcdt.controller.External*.*(..)) && execution(public * com.lcdt.controller.*Controller.*(..))")
public void log(){
}
/**
* 前置通知
* @param point
*/
@Before("log()")
public void beforeLog(JoinPoint point){
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
log.info("【请求 URL】:{}",request.getRequestURL());
log.info("【请求 IP】:{}",request.getRemoteAddr());
log.info("【请求类名】:{},【请求方法名】:{}",point.getSignature().getDeclaringTypeName(),point.getSignature().getName());
SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute("sysUserInfo");
if (userInfo != null) {
log.info("【请求人】:{}",userInfo.getLongin_name());
}
Map<String,String[]> paramMap = request.getParameterMap();
log.info("【请求参数】:{}",paramMap.toString());
Long start = System.currentTimeMillis();
request.setAttribute(START_TIME,start);
}
/**
* 环绕通知
* @param point
* @return
* @throws Throwable
*/
@Around("log()")
public Object arroundLog(ProceedingJoinPoint point) throws Throwable{
Object result = point.proceed();
log.info("【返回结果】:{}",result.toString());
return result;
}
/**
* 返回后通知
*/
@AfterReturning("log()")
public void afterReturningLog() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
Long start = (Long) request.getAttribute(START_TIME);
Long end = System.currentTimeMillis();
log.info("【请求耗时】:{}毫秒", end - start);
String header = request.getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(header);
log.info("【浏览器类型】:{},【操作系统】:{},【原始User-Agent】:{}", userAgent.getBrowser().toString(), userAgent.getOperatingSystem().toString(), header);
}
}
当然还有:
1.@After 后通知(After advice) :当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。
2.@AfterThrowing 抛出异常后通知(After throwing advice) : 在方法抛出异常退出时执行的通知。
需要的可以根据需求进行添加。
到此就可以打印、保存想要的日志,便于后期的分析了。