自定义打印日志 功能

pom.xml

<!--aspect注解-->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
</dependency>
<!--aspect注解-->

自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定义日志注解 -- 使用在方法上
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomLogAnnotation {

}

切面

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
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.time.LocalDateTime;

/**
 * 自定义日志
 */
@Component
@Aspect
@Slf4j
public class LogAnnotationAspect {

    @Pointcut("@annotation(com.example.goodscrawlerservice.annotation.CustomLogAnnotation)")
    public void logAspect() {
    }


    @Before("logAspect()")
    public void beforeLog(JoinPoint point) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String methodName = point.getSignature().getName();
        log.info("===============Method: " + methodName + "() begin===============");
        //执行时间
        LocalDateTime now = LocalDateTime.now();
        log.info("===============Time: " + now + " ===============");
        //请求URL
        log.info("===============URL: " + request.getRequestURL() + " ===============");
        //请求方式
        log.info("===============Request Method: " + request.getMethod() + " ===============");
        //controller 的请求全路径以及执行方法
        log.info("===============Class Method: " + point.getSignature().getDeclaringTypeName() + "." + methodName);
        //请求 IP
        log.info("===============IP : " + request.getRemoteHost() + " ===============");
        //请求参数
        log.info("Request Args : " + JSON.toJSONString(point.getArgs()) + " ===============");
    }

    @After("logAspect()")
    public void afterLog(JoinPoint point) {
        String methodName = point.getSignature().getName();
        log.info("===============Method: " + methodName + "() end===============");
    }

}

控制层方法使用

 

f0b846dd6404fa5d6dceade2c9cadcd4.png

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值