package com.zzhua.aspect;
import com.alibaba.fastjson.JSON;
import com.zzhua.enums.StatusEnums;
import com.zzhua.pojo.Log;
import com.zzhua.service.LogService;
import com.zzhua.utils.StringUtils;
import com.zzhua.utils.ThreadLocalContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
@Aspect
@Component
@Slf4j
public class RequestAspect {
@Autowired
private LogService logService;
@Pointcut("execution(* com.zzhua.controller..*(..))")
public void pointCut() {
}
@Before("pointCut()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
log.info("请求地址: {}", request.getRequestURI());
log.info("请求方式: {}", request.getMethod());
log.info("IP: {}" , StringUtils.getRemoteIp(request));
log.info("方法: {}" , joinPoint.getSignature());
log.info("参数: {}" , Arrays.toString(joinPoint.getArgs()));
Log logger = ThreadLocalContext.get().getLog();
logger.setLogUrl(request.getRequestURI());
logger.setLogParams( Arrays.toString(joinPoint.getArgs()));
logger.setLogStatus(StatusEnums.REQUEST_SUCCESS.getCode());
logger.setLogMethod(request.getMethod());
logger.setLogIp(StringUtils.getRemoteIp(request));
}
@After("pointCut()")
public void doAfter(){
}
@Around("pointCut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
long beginTime = System.currentTimeMillis();
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
long duration = endTime - beginTime;
log.info("耗时: {}" , duration);
ThreadLocalContext.get().getLog().setLogTime(duration);
return result;
}
@AfterReturning(value = "pointCut()",returning = "ret")
public void doAfterReturning(Object ret){
log.info("返回: {}",JSON.toJSONString(ret) );
Log logger = ThreadLocalContext.get().getLog();
logger.setLogResult(JSON.toJSONString(ret));
logger.setCreatedTime(new Date());
logService.insert(logger);
}
@AfterThrowing(value = "pointCut()", throwing = "ex")
public void doAfterThrowing(Exception ex){
Log logger = ThreadLocalContext.get().getLog();
logger.setLogStatus(StatusEnums.REQUEST_ERROR.getCode());
logger.setLogMessage(StringUtils.getPackageException(ex,"com.zzhua"));
logger.setLogTime(0L);
logger.setCreatedTime(new Date());
logService.insert(logger);
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-2598.html