两种方式aop 实现日志统计 后端api耗时
第一种注解方式实现
1:自定义注解
.
// An highlighted block
import java.lang.annotation.*;
/**
* @author shenyuan
* @date 2023-01-29 14:55
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TimeCostAnnotation {
}
2:定义切面
.
// An highlighted block
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.slf4j.MDC;
import org.springframework.stereotype.Component;
/**
* @author shenyuan
* @date 2023-01-29 15:01
*/
@Aspect
@Component
public class TimeCostAspect {
@Pointcut("@annotation(com.ebay.peoplex.config.TimeCostAnnotation)")
public void logPointcut(){
}
@Around("logPointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
Object proceed = point.proceed();
long costTime= System.currentTimeMillis()-beginTime;
MDC.put("time-cost", String.valueOf(costTime));
return proceed;
}
}
使用时直接在方法上加上注解
// A code block
var foo = 'bar';
// An highlighted block
@TimeCostAnnotation
@RequestMapping(value = "/country", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
第一直接在切点上定义执行点
作用在congtroller的方法上 ..*表示中间任意层级目录,*(..)表示方法
.
// An highlighted block
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.slf4j.MDC;
import org.springframework.stereotype.Component;
/**
* @author shenyuan
* @date 2023-01-29 15:01
*/
@Aspect
@Component
public class TimeCostAspect {
@Pointcut("execution(* com.ebay.peoplex..*.controller.*.*(..))")
public void logPointcut(){
}
@Around("logPointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
Object proceed = point.proceed();
long costTime= System.currentTimeMillis()-beginTime;
MDC.put("time-cost", String.valueOf(costTime));
return proceed;
}
}
调用后结果如下
1:自定义注解
.
{
"@timestamp": "2023-01-30T11:36:57.794+08:00",
"@version": "1",
"message": "***",
"logger_name": "***",
"thread_name": "***",
"level": "INFO",
"level_value": 20000,
"traceId": "3cc5bf2f-7489-49b5-93d3-22048a0b1c77",
"time-cost": "704",
"logname": "application-log",
"k8s-application": "app_name_IS_UNDEFINED",
"k8s-component": "component_name_IS_UNDEFINED",
"k8s-environment": "qa3",
"k8s-node": "node_name_IS_UNDEFINED",
"k8s-pod": "pod_name_IS_UNDEFINED",
"k8s-namespace": "pod_namespace_IS_UNDEFINED"
}
我的日志做了格式处理