Springboot 项目日志笔记

Springboot 项目日志笔记

Springboot 项目请求日志笔记

(一)方式一:(推荐使用)

package com.cloud.wl.hp.base.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 接口请求日志
 *
 * @author wanglin
 * @version 1.0
 * @date 2022-01-06 周四
 */
@Aspect
@Component
@Order(8)
@Slf4j
public class LogAspectPrint {
    @Pointcut("execution(* com.cloud.wl.hp.*.controller..*.*(..))" +
            "||execution(* com.cloud.wl.hp.*.impl..*.*(..))")
    private void aspect() {
    }

    @Around("aspect()")
    public Object around(JoinPoint joinPoint) throws Throwable {

        long timeMillis = System.currentTimeMillis();
        ProceedingJoinPoint proceedingJoinPoint = (ProceedingJoinPoint) joinPoint;
        Class clazz = proceedingJoinPoint.getTarget().getClass();
        String className = clazz.getName();
        String methodName = proceedingJoinPoint.getSignature().getName();
        Object[] objects = joinPoint.getArgs();

        // 将参数所在的数组转换成json
        Object[] arguments = new Object[objects.length];
        for (int i = 0; i < objects.length; i++) {
            if (objects[i] instanceof ServletRequest || objects[i] instanceof ServletResponse
                    || objects[i] instanceof MultipartFile) {
                continue;
            }
            arguments[i] = objects[i];
        }
        try {

            if (arguments != null && arguments.length > 0) {
                log.info("时间戳:{}, className--->:{}, methodName--->:{}, 参数:{}", timeMillis, className, methodName, JSONObject.toJSONString(arguments));
            } else {
                log.info("时间戳:{}, className--->:{}, methodName-->:{}, 无参数", timeMillis, className, methodName);
            }
        } catch (Exception e) {
            // 日志不能影响业务
        }
        long start = System.currentTimeMillis();
        Object result = ((ProceedingJoinPoint) joinPoint).proceed();
        long useTime = System.currentTimeMillis() - start;
        try {
            if (result == null) {
                log.info("时间戳:{}, className--->:{}, methodName--->:{}, 耗时:{}, 无返回值", timeMillis, className, methodName, useTime);
            } else {
                log.info("时间戳:{}, className--->:{}, methodName--->:{}, 耗时:{}, 返回值:{}", timeMillis, className, methodName, useTime, JSONObject.toJSONString(result));
            }
        } catch (Exception e) {
            // 日志不能影响业务
        }
        return result;
    }
}

(二)方式二

请求信息封装类:WebLogDTO

package com.cloud.wl.hp.base.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

/**
 * Controller层的日志封装类
 * 用于封装需要记录的日志信息,包括操作的描述、时间、消耗时间、url、请求参数和返回结果等信息。
 *
 * @author wanglin
 * @version 1.0
 * @date 2022-02-24 周四
 */
@Data
@Schema(description = "日志信息表")
public class WebLogDTO {
    /**
     * 操作描述
     */
    private String description;

    /**
     * 操作用户
     */
    private String username;

    /**
     * 操作时间
     */
    private Long startTime;

    /**
     * 消耗时间
     */
    private Integer spendTime;

    /**
     * 根路径
     */
    private String basePath;

    /**
     * URI
     */
    private String uri;

    /**
     * URL
     */
    private String url;

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

    /**
     * IP地址
     */
    private String ip;

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

    /**
     * 请求返回的结果
     */
    private Object result;
}

WebLogAspect 类

package com.cloud.wl.hp.base.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.cloud.wl.hp.base.dto.WebLogDTO;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wanglin
 * @version 1.0
 * @date 2022-02-24 周四
 */
@Aspect
@Component
@Order(1)
public class WebLogAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);

    @Pointcut("execution(* com.cloud.wl.hp.*.controller..*.*(..))" +
            "||execution(* com.cloud.wl.hp.*.impl..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息
        WebLogDTO webLog = new WebLogDTO();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(Operation.class)) {
            Operation apiOperation = method.getAnnotation(Operation.class);
            webLog.setDescription(apiOperation.description());
        }
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        webLog.setIp(request.getRemoteUser());
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        webLog.setSpendTime((int) (endTime - startTime));
        webLog.setStartTime(startTime);
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        LOGGER.info("{}", JSONUtil.parse(webLog));
        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.isEmpty(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;
        }
    }
}

注意:请求日志不能影响业务

关注林哥,持续更新哦!!!★,°:.☆( ̄▽ ̄)/$:.°★ 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值