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

SpringBoot自定义注解实现方法日志打印,拿来即用真香

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

SpringBoot自定义注解实现方法日志打印,拿来即用真香

思路

首先定义一个注解类
然后写注解切面类
最后在需要打印日志的方法上加上自定义注解即可
话不多上直接上代码:
注解类

import java.lang.annotation.*;


@documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodLogs {
     String methodName() default "";
}

切面类

package com.tencent.hr.corehr.common.aspect;

import cn.hutool.json.JSONUtil;
import com.tencent.hr.corehr.common.annotation.MethodLogs;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;


@Aspect
@Component
public class MethodLogsAspect {
    public final Logger logger =  LoggerFactory.getLogger(this.getClass());

    @Pointcut("@annotation(com.hr.corehr.common.annotation.MethodLogs)")
    public void pointCut() {

    }
    //该类就是为了实现一个目标打印加了该注解的请求参数,返回参数,响应时间,请求地址,方法名字
    @Around("pointCut()")
    public void beforeHandle(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        MethodLogs annotation = method.getAnnotation(MethodLogs.class);
        if (annotation == null) {
            annotation = joinPoint.getTarget().getClass().getAnnotation(MethodLogs.class);
        }
        String methodName = annotation.methodName();
        Long start = System.currentTimeMillis();
        //打印当前执行的方法名字
        logger.info("当前执行的方法名字为:{}" ,methodName);
        //打印请求地址
        HttpServletRequest request = getRequest();
        logger.info("这是当前方法的请求地址:{}" , request);
        //获取方法请求参数
        StringBuilder params = new StringBuilder();
        Object[] paramValue = joinPoint.getArgs();
        String[] paramName = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        if (paramValue != null) {
            for (int i = 0; i < paramValue.length; i++) {
                params.append(paramName[i]).append(":").append(paramValue[i]);
            }
        }
        //获取方法返回参数信息
        Object object = joinPoint.proceed();
        logger.info("这是当前方法的返回参数:{}", JSONUtil.toJsonStr(object));
        logger.info("这是当前方法执行完毕所消耗的时间:{}",(System.currentTimeMillis() - start));
    }

    //获取请求地址方法
    private HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        assert servletRequestAttributes != null;
        return servletRequestAttributes.getRequest();
    }

    
    @AfterThrowing(pointcut = "pointCut()", throwing = "e")
    public void throwIng(JoinPoint joinPoint, Throwable e) {
        logger.info("[异常日志]>>>>>>>>>>>>>>>>>>>>>>>>>开始进行记录");
        String stackTrace = stackTrace(e);
        HttpServletRequest request = getRequest();
        logger.info("[异常日志]>>>>>>>>>>>>>>>>>>>>>>>>>当前请求的Ip地址为:{}", "localhost");
        logger.info("[异常日志]>>>>>>>>>>>>>>>>>>>>>>>>>错误信息为:{}", stackTrace);
        logger.info("[异常日志]>>>>>>>>>>>>>>>>>>>>>>>>>异常日志记录完毕");
    }

    
    private static String stackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        try (PrintWriter pw = new PrintWriter(sw)) {
            throwable.printStackTrace(pw);
            return sw.toString();
        }
    }

}

测试方法
@PostMapping("/test")
@MethodLogs(methodName = "测试日志打印注解方法") 
public String testName(@RequestBody List engNameList) {
return "这是返回参数";
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/324874.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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