java 记录日志切面工具类

  一些项目,特别是接收一些老项目,里面都没有很规范的打印日志,一个一个添加不现实,编写一个切面工具类,直接打印接口的请求出入参数

@Aspect
@Component
public class LogAopAspect {
    private final Logger log = ESAPI.getLogger(this.getClass());

    private static final String REGEX = "#.+?#";
    private final String REQUEST_MESSAGE_BODY = "发送请求:#方法名#:#请求路径#:请求入参:#请求体#";
    private final String RESPONSE_MESSAGE_BODY = "请求响应:#方法名#:#请求路径#:响应出参:#响应体#";

    @Pointcut("execution(* cn.com.aia.acn.bizportal.controller..*.*(..)) ")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object logPointAround(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        String clzName = signature.getDeclaringTypeName().substring(signature.getDeclaringTypeName().lastIndexOf(".")+1,signature.getDeclaringTypeName().length());
        String methodDesc = clzName + "." + signature.getName();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return printLog(methodDesc, request, pjp);
    }

    private Object printLog(String methodDesc, HttpServletRequest request, ProceedingJoinPoint pjp) throws Throwable {
        String method = request.getMethod();
        if (method.equals("GET")) {
            Map<String, String[]> parameterMap = request.getParameterMap();
            String content1 = replaceString(REQUEST_MESSAGE_BODY,methodDesc, request.getRequestURI(), JSON.toJSONString(parameterMap));
            log.info(Logger.EVENT_SUCCESS,content1);
        } else if (method.equals("POST")) {
            //获取请求body
            byte[] bodyBytes = StreamUtils.copyToByteArray(request.getInputStream());
            String body = new String(bodyBytes, request.getCharacterEncoding());
            String content2 = replaceString(REQUEST_MESSAGE_BODY,methodDesc, request.getRequestURI(), body);
            log.info(Logger.EVENT_SUCCESS,content2);
        }
        Object obj = pjp.proceed();

        String content3 = replaceString(RESPONSE_MESSAGE_BODY,methodDesc, request.getRequestURI(), JSON.toJSONString(obj));
        log.info(Logger.EVENT_SUCCESS,content3);
        return obj;
    }
    public static String replaceString(String text, String ...values) {
        for (String value : values) {
            if(StringUtils.isBlank(value)) {
                value = "";
            }
            text = text.replaceFirst(REGEX,value);
        }
        return text;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值