0
点赞
收藏
分享

微信扫一扫

springboot统一自定义日志

Alex富贵 2022-01-22 阅读 55

1、定义日志输出的属性

@Data
public class WebLog {

    /**
     * 操作描述
     */
    private String description;

    /**
     * URL
     */
    private String url;

    /**
     * Header
     */
    private String token;

    /**
     * 请求类型
     */
    private String method;

    /**
     * 请求参数
     */
    private Object requestParameter;

    /**
     * IP地址
     */
    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<String, String[]> 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<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            // 将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            // 将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (StringUtils.hasLength(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }

        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}

3、配置文件中日志输出自定义级别

# 日志
logging:
  level:
    root: info
    com.xxx.xxx: info
举报

相关推荐

0 条评论