切面主要记录传参和返回值,代码如下:
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.scheduling.annotation.Async;
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;
/**
* controller 切面
* @author yuhao
**/
@Slf4j
@Aspect
@Component
public class HttpLogAspect {
/**
* 两个..代表所有子目录,最后括号里的两个..代表所有参数
*/
@Pointcut("execution(public * com.xx.controller..*.*(..))")
public void logPointCut() {
}
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
log.info("请求地址 : " + request.getRequestURL().toString());
log.info("HTTP方法 {} ,IP地址 {} ,contentType: {}", request.getMethod(), request.getRemoteAddr() , request.getContentType());
log.info("类名 {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
log.info("请求参数 {}", Arrays.toString(joinPoint.getArgs()));
}
/**
* returning的值和doAfterReturning的参数名一致
*/
@AfterReturning(returning = "ret", pointcut = "logPointCut()")
public void doAfterReturning(Object ret) {
log.info("返回值: {}", ret);
}
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
// ob 为方法的返回值
Object ob = pjp.proceed();
log.info("耗时 {}", (System.currentTimeMillis() - startTime));
return ob;
}
@Async
public void log(String httpWrapper) {
// 日志入库
}
}
异常处理:
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* @author yuhao
* @date 20-4-22 下午3:35
* @version V1.0
**/
@Slf4j
@ControllerAdvice
public class ExpHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity handleException(Exception e) {
log.error("",e);
//SdkAuthResp此类是使用lombok注解的建造者模式的类,返回的状态码使用枚举
SdkAuthResp build = SdkAuthResp.builder().status(1001).build();
return new ResponseEntity<>(build, HttpStatus.OK);
}
//ParamNullException是自定义的异常类
@ExceptionHandler(ParamNullException.class)
public ResponseEntity<SdkAuthResp> handleException(ParamNullException e) {
log.error("",e);
SdkAuthResp build = SdkAuthResp.builder().status(1002).build();
return new ResponseEntity<>(build, HttpStatus.CREATED);
}
}
网友评论