SpringAOP统一处理日志信息

在程序中日志是很重要的一部分信息,我们需要记录的业务日志十分多,因此为了方便日志处理,我们利用AOP的原理进行日志处理。

拿controller的接口为例,我们定义切面为controller层的所有类,
利用前置增强方法,获取controller层每个请求的请求对象信息;进行日志打印
利用后置增强方法;获取controller层每个请求的返回对象信息;进行日志打印。

代码如下

package com.hyl.springboot.aop;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyl.springboot.zUtils.utils.JsonUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
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.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

@Aspect
@Component
/*@Slf4j*/
//打印请求的结果日志信息
public class WebLogAspect {
    private static Logger log = LoggerFactory.getLogger(JsonUtil.class);
	//定义切面
    //	@Pointcut("execution(public * com.aiyijia.springbootdemo.controller..*.*(..))")
    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) || @annotation(org.springframework.web.bind.annotation.GetMapping) || @annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void webLog() {
    }


    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        MDC.clear();
        MDC.put("uuid", UUID.randomUUID().toString().replace("-", ""));
        log.info("#####请求开始####################################");
        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
//		log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = (String) enu.nextElement();
            log.info("name:{" + name + "},value:{" + request.getParameter(name) + "}");
        }
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
        // 处理完请求,返回内容
        if (log.isInfoEnabled()) {
            log.info("RESPONSE : " + ret);
            log.info("###################################请求结束######");
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        try {
            if (log.isDebugEnabled()) {
                log.debug("returnValue={}", mapper.writeValueAsString(ret));
            }
        } catch (Exception exc) {
            log.error("拦截器异常", exc);
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

博客胡

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值