1、定义日志输出的属性
@Data
public class WebLog {
private String description;
private String url;
private String token;
private String method;
private Object requestParameter;
private String ip;
private String username;
private Object parameter;
private Long startTime;
private Long spendTime;
private Object result;
}
2、aop切面处理(需要导入aop的包)
@Aspect
@Component
@Order(1)
public class WebLogAspect {
private static final Logger log = LoggerFactory.getLogger(WebLogAspect.class);
@Value("${jwt.tokenHeader:Authorization}")
private String tokenHeader;
@Pointcut("execution(public * com.xxx.xxx.controller.*.*(..))")
public void webLog() {
}
@Pointcut("execution(public * com.xxx.xxx.exception.APIExceptionHandler.*(..))")
public void exceptionLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
}
@AfterReturning(value = "webLog()", returning = "ret")
public void doAfterReturning(Object ret) throws Throwable {
}
@Around("webLog() || exceptionLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
// 获取当前请求对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录请求信息
WebLog webLog = new WebLog();
Object result = joinPoint.proceed();
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method.isAnnotationPresent(ApiOperation.class)) {
ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
webLog.setDescription(apiOperation.value());
}
long endTime = System.currentTimeMillis();
webLog.setIp(request.getRemoteUser());
webLog.setMethod(request.getMethod());
webLog.setToken(request.getHeader(tokenHeader));
webLog.setParameter(getParameter(method, joinPoint.getArgs()));
Map requestParameterMap = request.getParameterMap();
webLog.setRequestParameter(requestParameterMap);
webLog.setResult(result);
webLog.setSpendTime(endTime - startTime);
webLog.setStartTime(startTime);
webLog.setUrl(request.getRequestURL().toString());
// JSON 按WebLog顺序输出
JSONObject jsonObj = new JSONObject(true);
Field[] fields = webLog.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
jsonObj.append(field.getName(), field.get(webLog));
}
log.info("{}", jsonObj);
return result;
}
private Object getParameter(Method method, Object[] args) {
List
3、配置文件中日志输出自定义级别
# 日志
logging:
level:
root: info
com.xxx.xxx: info



