栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

无自定义注解式日志切面

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

无自定义注解式日志切面

项目场景:

项目中需要通过日志记录应用的上下游调用信息。


具体实现

通过切面来打印接口的调用信息
代码:

import lombok.extern.slf4j.Slf4j;
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.stereotype.Component;

import java.util.Arrays;


@Aspect
@Component
@Slf4j
public class LogRecodeAspect {

    @Pointcut("execution( * com.hx.order.center.api..*.*(..))")
    public void apiLog() {
    }

    @Pointcut("execution( * com.hx.order.center.integration..*.*(..))")
    public void integrationLog() {
    }

    @Around(value = "apiLog()")
    public Object apiLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        String model = "api";
        return recordLog(proceedingJoinPoint, model);
    }

    @Around(value = "integrationLog()")
    public Object integrationLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        String model = "integration";
        return recordLog(proceedingJoinPoint, model);
    }

    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint, String model) throws Throwable {
        long startTime = System.currentTimeMillis();
        String declaringTypeName = proceedingJoinPoint.getSignature().getDeclaringTypeName();
        String simpleName = declaringTypeName.substring(declaringTypeName.lastIndexOf('.') + 1);
        String path = simpleName + "." + proceedingJoinPoint.getSignature().getName();
        //发生异常后,手动捕获后抛出,由全局异常捕获统一处理
        try {
            Object object = proceedingJoinPoint.proceed();
            long time = System.currentTimeMillis() - startTime;
            String info = String.format("model:%s path:%s request:%s response:%s time:%dms",
                    model, path, Arrays.toString(proceedingJoinPoint.getArgs()), object, time);
            log.info(info);
            return object;
        } catch (Throwable e) {
            long time = System.currentTimeMillis() - startTime;
            String error = String.format("model:%s path:%s request:%s exception:%s time:%dms",
                    model, path, Arrays.toString(proceedingJoinPoint.getArgs()), e, time);
            log.error(error);
            throw e;
        }
    }

}
如有问题,请留言!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/998755.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号