访问日志切面的一些思考

访问日志切面的一些思考

背景

自定义切面, 配合日志框架, 做访问日志记录.

说明

这里只是提供一些思路, 不能直接使用.
这里只是提供一些思路, 不能直接使用.
这里只是提供一些思路, 不能直接使用.

切面参考代码

@Aspect
@Component
@Slf4j
public class AccessLogRecorder {
    private static final int TRUNCAT_LENTH = 500;

    @Around("execution(* com.moxi.mogublog.admin.restapi.*Api.*(..))")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        Object[] args = proceedingJoinPoint.getArgs();
        Stream<?> stream = ObjectUtil.isEmpty(args) ? Stream.empty() : Arrays.stream(args.clone());
        /**
         * HttpServletRequest: 不能被序列化, 报错: It is illegal to call this method if the current request is not in asynchron
         * HttpServletResponse: 不能被序列化, 报错: java.lang.IllegalStateExcetion: getOutputStream() has alreadly been called for this response
         * MultipartFile: fastjson 不能序列化MultipartFile
         */
        Collection<Object> logArgs = stream.filter(arg -> !(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)
                && !(arg instanceof MultipartFile) && !(arg instanceof MultipartFile[])
        ).collect(Collectors.toList());

        // hostIp和端口
        String hostAndPort = request.getRemoteHost() + ":" + request.getRemotePort();

        // 请求方法
        String requestMethod = request.getMethod();

        // 接口路径
        String servletPath = request.getServletPath();

        // 请求参数: 这里没有测试
        String requestInfo = JSONUtil.toJsonStr(logArgs);

        // 请求人
        // UserContext.UserInfo userInfo = UserContext.getInstance.getCurrentUser();
        String operator = "";
//        if (userInfo != null) {
//            operator = userInfo.getEmployeeNumber() + "[" + userInfo.getId() + "]";
//        }

        // 请求人IP
        // String operatorIp = IpAddressUtils.getIPAddress(request);

        // 请求人信息
        // String operatorInfo = operator + operatorIp;

        // 响应信息
        String responseInfo = null;
        long startTime = System.currentTimeMillis();
        try {
            // 返回值
            Object result = proceedingJoinPoint.proceed();
            String jsonStr = JSONUtil.toJsonStr(result);

            if (jsonStr.length() > TRUNCAT_LENTH) {
                jsonStr = jsonStr.substring(0, TRUNCAT_LENTH) + "...";
            }

            requestInfo = jsonStr;

            // 耗时
            long timeConsuming = System.currentTimeMillis() - startTime;

            log.info("{} --- {} --- {} --- {} --- {} --- {} --- {}ms", hostAndPort, requestMethod, servletPath,
                    requestInfo, responseInfo, operator, timeConsuming);
            return result;
        } catch (Throwable t) {
            requestInfo = t.getClass().getName() + ":" + t.getMessage();
            // 耗时
            long timeConsuming = System.currentTimeMillis() - startTime;
            log.info("{} --- {} --- {} --- {} --- {} --- {} --- {}ms", hostAndPort, requestMethod, servletPath,
                    requestInfo, responseInfo, operator, timeConsuming);
            throw t;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以通过在接口调用前后添加切面(Aspect),在接口调用前记录请求的参数和时间戳,在接口调用后记录响应结果和时间戳。具体地,您可以在切面中使用 `@Before` 注解和 `@AfterReturning` 注解来分别捕捉接口调用前和调用后的信息。在 `@AfterReturning` 注解中,您可以通过返回值参数 `Object returnValue` 来获取接口的返回结果,然后对其进行处理。这里提供一个简单的示例: ```java @Component @Aspect public class InterfaceLogAspect { private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceLogAspect.class); @Before("execution(* com.example.demo.service.impl.*.*(..))") public void before(JoinPoint joinPoint) { LOGGER.info("Method {}() is invoked with args {} at {}.", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()), LocalDateTime.now()); } @AfterReturning(pointcut = "execution(* com.example.demo.service.impl.*.*(..))", returning = "returnValue") public void afterReturning(JoinPoint joinPoint, Object returnValue) { LOGGER.info("Method {}() is finished at {} with return value {}.", joinPoint.getSignature().getName(), LocalDateTime.now(), returnValue); } } ``` 在上述示例中,我们定义了一个名为 `InterfaceLogAspect` 的切面,并使用 `@Before` 和 `@AfterReturning` 注解分别捕捉接口调用前和调用后的信息。其中,我们使用 `JoinPoint` 对象来获取调用方法的名称和参数,并使用 `LocalDateTime` 来记录时间戳。在 `@AfterReturning` 注解中,我们使用 `Object returnValue` 参数来获取接口返回的结果,并通过 `LOGGER` 对象来打印日志信息。您可以根据自己的需求修改上述示例中的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值