java如何实现统一打印入参出参等日志

其他教程   发布日期:2024年10月28日   浏览次数:321

这篇文章主要介绍“java如何实现统一打印入参出参等日志”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“java如何实现统一打印入参出参等日志”文章能帮助大家解决问题。

    1.背景

    SpringBoot项目中,之前都是在controller方法的第一行手动打印 log,return之前再打印返回值。有多个返回点时,就需要出现多少重复代码,过多的非业务代码显得十分凌乱。

    本文将采用AOP 配置自定义注解实现 入参、出参的日志打印(方法的入参和返回值都采用 fastjson 序列化)。

    2.设计思路

    将特定包下所有的controller生成代理类对象,并交由Spring容器管理,并重写invoke方法进行增强(入参、出参的打印).

    3.核心代码

    3.1 自定义注解

    1. @Target(ElementType.TYPE)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. @Import({InteractRecordBeanPostProcessor.class})
    5. public @interface EnableInteractRecord {
    6. /**
    7. * app对应controller包名
    8. */
    9. String[] basePackages() default {};
    10. /**
    11. * 排除某些包
    12. */
    13. String[] exclusions() default {};
    14. }

    3.2 实现BeanFactoryPostProcessor接口

    作用:获取EnableInteractRecord注解对象,用于获取需要创建代理对象的包名,以及需要排除的包名

    1. @Component
    2. public class InteractRecordFactoryPostProcessor implements BeanFactoryPostProcessor {
    3. private static Logger logger = LoggerFactory.getLogger(InteractRecordFactoryPostProcessor.class);
    4. private EnableInteractRecord enableInteractRecord;
    5. @Override
    6. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    7. try {
    8. String[] names = beanFactory.getBeanNamesForAnnotation(EnableInteractRecord.class);
    9. for (String name : names) {
    10. enableInteractRecord = beanFactory.findAnnotationOnBean(name, EnableInteractRecord.class);
    11. logger.info("开启交互记录 ", enableInteractRecord);
    12. }
    13. } catch (Exception e) {
    14. logger.error("postProcessBeanFactory() Exception ", e);
    15. }
    16. }
    17. public EnableInteractRecord getEnableInteractRecord() {
    18. return enableInteractRecord;
    19. }
    20. }

    3.3 实现MethodInterceptor编写打印日志逻辑

    作用:进行入参、出参打印,包含是否打印逻辑

    1. @Component
    2. public class ControllerMethodInterceptor implements MethodInterceptor {
    3. private static Logger logger = LoggerFactory.getLogger(ControllerMethodInterceptor.class);
    4. // 请求开始时间
    5. ThreadLocal<Long> startTime = new ThreadLocal<>();
    6. private String localIp = "";
    7. @PostConstruct
    8. public void init() {
    9. try {
    10. localIp = InetAddress.getLocalHost().getHostAddress();
    11. } catch (UnknownHostException e) {
    12. logger.error("本地IP初始化失败 : ", e);
    13. }
    14. }
    15. @Override
    16. public Object invoke(MethodInvocation invocation) {
    17. pre(invocation);
    18. Object result;
    19. try {
    20. result = invocation.proceed();
    21. post(invocation, result);
    22. return result;
    23. } catch (Throwable ex) {
    24. logger.error("controller 执行异常: ", ex);
    25. error(invocation, ex);
    26. }
    27. return null;
    28. }
    29. public void error(MethodInvocation invocation, Throwable ex) {
    30. String msgText = ex.getMessage();
    31. logger.info(startTime.get() + " 异常,请求结束");
    32. logger.info("RESPONSE : " + msgText);
    33. logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
    34. }
    35. private void pre(MethodInvocation invocation) {
    36. long now = System.currentTimeMillis();
    37. startTime.set(now);
    38. logger.info(now + " 请求开始");
    39. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    40. HttpServletRequest request = attributes.getRequest();
    41. logger.info("URL : " + request.getRequestURL().toString());
    42. logger.info("HTTP_METHOD : " + request.getMethod());
    43. logger.info("REMOTE_IP : " + getRemoteIp(request));
    44. logger.info("LOCAL_IP : " + localIp);
    45. logger.info("METHOD : " + request.getMethod());
    46. logger.info("CLASS_METHOD : " + getTargetClassName(invocation) + "." + invocation.getMethod().getName());
    47. // 获取请求头header参数
    48. Map<String, String> map = new HashMap<String, String>();
    49. Enumeration<String> headerNames = request.getHeaderNames();
    50. while (headerNames.hasMoreElements()) {
    51. String key = (String) headerNames.nextElement();
    52. String value = request.getHeader(key);
    53. map.put(key, value);
    54. }
    55. logger.info("HEADERS : " + JSONObject.toJSONString(map));
    56. Date createTime = new Date(now);
    57. // 请求报文
    58. Object[] args = invocation.getArguments();// 参数
    59. String msgText = "";
    60. Annotation[][] annotationss = invocation.getMethod().getParameterAnnotations();
    61. for (int i = 0; i < args.length; i++) {
    62. Object arg = args[i];
    63. if (!(arg instanceof ServletRequest)
    64. && !(arg instanceof ServletResponse)
    65. && !(arg instanceof Model)) {
    66. RequestParam rp = null;
    67. Annotation[] annotations = annotationss[i];
    68. for (Annotation annotation : annotations) {
    69. if (annotation instanceof RequestParam) {
    70. rp = (RequestParam) annotation;
    71. }
    72. }
    73. if (msgText.equals("")) {
    74. msgText += (rp != null ? rp.value() + " = " : " ") + JSONObject.toJSONString(arg);
    75. } else {
    76. msgText += "," + (rp != null ? rp.value() + " = " : " ") + JSONObject.toJSONString(arg);
    77. }
    78. }
    79. }
    80. logger.info("PARAMS : " + msgText);
    81. }
    82. private void post(MethodInvocation invocation, Object result) {
    83. logger.info(startTime.get() + " 请求结束");
    84. if (!(result instanceof ModelAndView)) {
    85. String msgText = JSONObject.toJSONString(result);
    86. logger.info("RESPONSE : " + msgText);
    87. }
    88. logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
    89. }
    90. private String getRemoteIp(HttpServletRequest request) {
    91. String remoteIp = null;
    92. String remoteAddr = request.getRemoteAddr();
    93. String forwarded = request.getHeader("X-Forwarded-For");
    94. String realIp = request.getHeader("X-Real-IP");
    95. if (realIp == null) {
    96. if (forwarded == null) {
    97. remoteIp = remoteAddr;
    98. } else {
    99. remoteIp = remoteAddr + "/" + forwarded.split(",")[0];
    100. }
    101. } else {
    102. if (realIp.equals(forwarded)) {
    103. remoteIp = realIp;
    104. } else {
    105. if (forwarded != null) {
    106. forwarded = forwarded.split(",")[0];
    107. }
    108. remoteIp = realIp + "/" + forwarded;
    109. }
    110. }
    111. return remoteIp;
    112. }
    113. private String getTargetClassName(MethodInvocation invocation) {
    114. String targetClassName = "";
    115. try {
    116. targetClassName = AopTargetUtils.getTarget(invocation.getThis()).getClass().getName();
    117. } catch (Exception e) {
    118. targetClassName = invocation.getThis().getClass().getName();
    119. }
    120. return targetClassName;
    121. }
    122. }

    AopTargetUtils:

    1. public class AopTargetUtils {
    2. /**
    3. * 获取 目标对象
    4. * @param proxy 代理对象
    5. * @return
    6. * @throws Exception
    7. */
    8. public static Object getTarget(Object proxy) throws Exception {
    9. if(!AopUtils.isAopProxy(proxy)) {
    10. return proxy;//不是代理对象
    11. }
    12. if(AopUtils.isJdkDynamicProxy(proxy)) {
    13. return getJdkDynamicProxyTargetObject(proxy);
    14. } else { //cglib
    15. return getCglibProxyTargetObject(proxy);
    16. }
    17. }
    18. private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
    19. Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
    20. h.setAccessible(true);
    21. Object dynamicAdvisedInterceptor = h.get(proxy);
    22. Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
    23. advised.setAccessible(true);
    24. Object target = ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
    25. return getTarget(target);
    26. }
    27. private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
    28. Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
    29. h.setAccessible(true);
    30. AopProxy aopProxy = (AopProxy) h.get(proxy);
    31. Field advised = aopProxy.getClass().getDeclaredField("advised");
    32. advised.setAccessible(true);
    33. Object target = ((AdvisedSupport)advised.get(aopProxy)).getTargetSource().getTarget();
    34. return getTarget(target);
    35. }
    36. }

    3.4 实现BeanPostProcessor接口

    作用:筛选出需要生成代理的类,并生成代理类,返回给Spring容器管理。

    1. public class InteractRecordBeanPostProcessor implements BeanPostProcessor {
    2. private static Logger logger = LoggerFactory.getLogger(InteractRecordBeanPostProcessor.class);
    3. @Autowired
    4. private InteractRecordFactoryPostProcessor interactRecordFactoryPostProcessor;
    5. @Autowired
    6. private ControllerMethodInterceptor controllerMethodInterceptor;
    7. private String BASE_PACKAGES[];//需要拦截的包
    8. private String EXCLUDING[];// 过滤的包
    9. //一层目录匹配
    10. private static final String ONE_REGEX = "[a-zA-Z0-9_]+";
    11. //多层目录匹配
    12. private static final String ALL_REGEX = ".*";
    13. private static final String END_ALL_REGEX = "*";
    14. @PostConstruct
    15. public void init() {
    16. EnableInteractRecord ir = interactRecordFactoryPostProcessor.getEnableInteractRecord();
    17. BASE_PACKAGES = ir.basePackages();
    18. EXCLUDING = ir.exclusions();
    19. }
    20. @Override
    21. public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    22. try {
    23. if (interactRecordFactoryPostProcessor.getEnableInteractRecord() != null) {
    24. // 根据注解配置的包名记录对应的controller层
    25. if (BASE_PACKAGES != null && BASE_PACKAGES.length > 0) {
    26. Object proxyObj = doEnhanceForController(bean);
    27. if (proxyObj != null) {
    28. return proxyObj;
    29. }
    30. }
    31. }
    32. } catch (Exception e) {
    33. logger.error("postProcessAfterInitialization() Exception ", e);
    34. }
    35. return bean;
    36. }
    37. @Override
    38. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    39. return bean;
    40. }
    41. private Object doEnhanceForController(Object bean) {
    42. String beanPackageName = getBeanPackageName(bean);
    43. if (StringUtils.isNotBlank(beanPackageName)) {
    44. for (String basePackage : BASE_PACKAGES) {
    45. if (matchingPackage(basePackage, beanPackageName)) {
    46. if (EXCLUDING != null && EXCLUDING.length > 0) {
    47. for (String excluding : EXCLUDING) {
    48. if (matchingPackage(excluding, beanPackageName)) {
    49. return bean;
    50. }
    51. }
    52. }
    53. Object target = null;
    54. try {
    55. target = AopTargetUtils.getTarget(bean);
    56. } catch (Exception e) {
    57. logger.error("AopTargetUtils.getTarget() exception", e);
    58. }
    59. if (target != null) {
    60. boolean isController = target.getClass().isAnnotationPresent(Controller.class);
    61. boolean isRestController = target.getClass().isAnnotationPresent(RestController.class);
    62. if (isController || isRestController) {
    63. ProxyFactory proxy = new ProxyFactory();
    64. proxy.setTarget(bean);
    65. proxy.addAdvice(controllerMethodInterceptor);
    66. return proxy.getProxy();
    67. }
    68. }
    69. }
    70. }
    71. }
    72. return null;
    73. }
    74. private static boolean matchingPackage(String basePackage, String currentPackage) {
    75. if (StringUtils.isEmpty(basePackage) || StringUtils.isEmpty(currentPackage)) {
    76. return false;
    77. }
    78. if (basePackage.indexOf("*") != -1) {
    79. String patterns[] = StringUtils.split(basePackage, ".");
    80. for (int i = 0; i < patterns.length; i++) {
    81. String patternNode = patterns[i];
    82. if (patternNode.equals("*")) {
    83. patterns[i] = ONE_REGEX;
    84. }
    85. if (patternNode.equals("**")) {
    86. if (i == patterns.length - 1) {
    87. patterns[i] = END_ALL_REGEX;
    88. } else {
    89. patterns[i] = ALL_REGEX;
    90. }
    91. }
    92. }
    93. String basePackageRegex = StringUtils.join(patterns, "\.");
    94. Pattern r = Pattern.compile(basePackageRegex);
    95. Matcher m = r.matcher(currentPackage);
    96. return m.find();
    97. } else {
    98. return basePackage.equals(currentPackage);
    99. }
    100. }
    101. private String getBeanPackageName(Object bean) {
    102. String beanPackageName = "";
    103. if (bean != null) {
    104. Class<?> beanClass = bean.getClass();
    105. if (beanClass != null) {
    106. Package beanPackage = beanClass.getPackage();
    107. if (beanPackage != null) {
    108. beanPackageName = beanPackage.getName();
    109. }
    110. }
    111. }
    112. return beanPackageName;
    113. }
    114. }

    3.5 启动类配置注解

    1. @EnableInteractRecord(basePackages = com.test.test.controller”,exclusions = com.test.demo.controller”)

    以上即可实现入参、出参日志统一打印,并且可以将特定的controller集中管理,并不进行日志的打印(及不进生成代理类)。

    4.出现的问题(及其解决办法)

    实际开发中,特定不需要打印日志的接口,无法统一到一个包下。大部分需要打印的接口,和不需要打印的接口,大概率会参杂在同一个controller中,根据以上设计思路,无法进行区分。

    解决办法:

    自定义排除入参打印注解

    1. @Target(ElementType.METHOD)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. public @interface ExcludeReqLog {
    5. }

    自定义排除出参打印注解

    1. @Target(ElementType.METHOD)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. public @interface ExcludeRespLog {
    5. }

    增加逻辑

    1. // 1.在解析requestParam之前进行判断
    2. Method method = invocation.getMethod();
    3. Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
    4. boolean flag = true;
    5. for (Annotation annotation : declaredAnnotations) {
    6. if (annotation instanceof ExcludeReqLog) {
    7. flag = false;
    8. }
    9. }
    10. if (!flag) {
    11. logger.info("该方法已排除,不打印入参");
    12. return;
    13. }
    14. // 2.在解析requestResp之前进行判断
    15. Method method = invocation.getMethod();
    16. Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
    17. boolean flag = true;
    18. for (Annotation annotation : declaredAnnotations) {
    19. if (annotation instanceof ExcludeRespLog) {
    20. flag = false;
    21. }
    22. }
    23. if (!flag) {
    24. logger.info("该方法已排除,不打印出参");
    25. return;
    26. }

    使用方法

    1. // 1.不打印入参
    2. @PostMapping("/uploadImg")
    3. @ExcludeReqLog
    4. public Result<List<Demo>> uploadIdeaImg(@RequestParam(value = "imgFile", required = false) MultipartFile[] imgFile) {
    5. return demoService.uploadIdeaImg(imgFile);
    6. }
    7. //2.不打印出参
    8. @PostMapping("/uploadImg")
    9. @ExcludeRespLog
    10. public Result<List<Demo>> uploadIdeaImg(@RequestParam(value = "imgFile", required = false) MultipartFile[] imgFile) {
    11. return demoService.uploadIdeaImg(imgFile);
    12. }

    以上就是java如何实现统一打印入参出参等日志的详细内容,更多关于java如何实现统一打印入参出参等日志的资料请关注九品源码其它相关文章!