如何使用Spring AOP和SPring引导进行日志记录 [英] how to log with Spring AOP and SPring boot

查看:61
本文介绍了如何使用Spring AOP和SPring引导进行日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用与本示例教程相同的类LoggingAspect https://www.javaguides.net/2019/05/spring-boot-spring-aop-logging-example-tutorial.html ,但是当我调用控制器方法时,我只会得到控制台上的这些消息

i use the same class LoggingAspect as in this example tutorial https://www.javaguides.net/2019/05/spring-boot-spring-aop-logging-example-tutorial.html, but when i call a controller methode i get only those messages on console

11-05-2020 13:30:27.742 [http-nio-8080-exec-7] INFO  o.a.c.c.C.[.[localhost].[/appged].log - Initializing Spring DispatcherServlet 'dispatcherServlet'
11-05-2020 13:30:27.742 [http-nio-8080-exec-7] INFO  o.s.web.servlet.DispatcherServlet.initServletBean - Initializing Servlet 'dispatcherServlet'
11-05-2020 13:30:27.771 [http-nio-8080-exec-7] INFO  o.s.web.servlet.DispatcherServlet.initServletBean - Completed initialization in 29 ms

日志记录方面:包com.app.ged.api.aspect;

la classe le Logging Aspect : package com.app.ged.api.aspect;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Aspect for logging execution of service and repository Spring components.
 * 
 *
 */
@Aspect
@Component
public class LoggingAspect {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * Pointcut that matches all repositories, services and Web REST endpoints.
     */
    @Pointcut("within(@org.springframework.stereotype.Repository *)" +
        " || within(@org.springframework.stereotype.Service *)" +
        " || within(@org.springframework.web.bind.annotation.RestController *)")
    public void springBeanPointcut() {
        // Method is empty as this is just a Pointcut, the implementations are in the advices.
    }

    /**
     * Pointcut that matches all Spring beans in the application's main packages.
     */
    @Pointcut("within(com.app.ged.api.repository.*)"+
        " || within(com.app.ged.api.service.*)"+
        " || within(com.app.ged.api.controller.*)")
    public void applicationPackagePointcut() {
        // Method is empty as this is just a Pointcut, the implementations are in the advices.
    }

    /**
     * Advice that logs methods throwing exceptions.
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
            log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
    }

    /**
     * Advice that logs when a method is entered and exited.
     *
     * @param joinPoint join point for advice
     * @return result
     * @throws Throwable throws IllegalArgumentException
     */
    @Around("applicationPackagePointcut() && springBeanPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        if (log.isDebugEnabled()) {
            log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
        }
        try {
            Object result = joinPoint.proceed();
            if (log.isDebugEnabled()) {
                log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                    joinPoint.getSignature().getName(), result);
            }
            return result;
        } catch (IllegalArgumentException e) {
            log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
                joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
            throw e;
        }
    }


}

我的logback-spring.xml

my logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>
          %d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n
      </pattern>
    </encoder>
  </appender>

  <appender name="SAVE-TO-FILE" class="ch.qos.logback.core.FileAppender">
    <file>${LOG_PATH}/log-appGed.log</file>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
      <Pattern>
        %d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n
      </Pattern>
    </encoder>
  </appender>

  <springProfile name="pc">
    <root level="info">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="SAVE-TO-FILE"/>
    </root>
     <logger name="com.app.ged.api.controller" additivity="false" level="debug">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="SAVE-TO-FILE"/>
    </logger>
    <logger name="com.app.ged.api.service" additivity="false" level="debug">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="SAVE-TO-FILE"/>
    </logger>
  </springProfile>

  <springProfile name="dev">
    <root level="info">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="SAVE-TO-FILE"/>
    </root>
    <logger name="com.app.api.service" additivity="false" level="debug">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="SAVE-TO-FILE"/>
    </logger>
  </springProfile>

  <springProfile name="prod">
    <root level="info">
      <appender-ref ref="SAVE-TO-FILE"/>
    </root>
    <logger name="com.app.ged.api.service" additivity="false" level="error">
      <appender-ref ref="SAVE-TO-FILE"/>
    </logger>
  </springProfile>

</configuration>

application.properties

application.properties

#logging 
spring.profiles.active=pc
logging.path=C:/logs

推荐答案

运行的活动配置文件是 pc ,并且方面日志用于 error 调试

Active profile for the run is pc and aspect logs are either for error or for debug

配置文件 pc 的当前根级别配置是该应用程序的 info .

The current root level configuration for profile pc is info for the application.

您可以按照以下说明将根日志级别设置为 debug 而不是 info .这是一个应用程序范围的设置

Either you may set the root log level as debug instead of info as follows . This is an application wide setting

  <springProfile name="pc">
    <root level="debug">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="SAVE-TO-FILE"/>
    </root>
    ..
  </springProfile>

或将方面包类的日志级别设置为 debug

or set the log level to debug for the aspect package classes

  <springProfile name="pc">
    <root level="info">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="SAVE-TO-FILE"/>
    </root>
    <logger name="com.app.ged.api.aspect" additivity="false" level="debug">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="SAVE-TO-FILE"/>
    </logger>     
    <logger name="com.app.ged.api.controller" additivity="false" level="debug">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="SAVE-TO-FILE"/>
    </logger>
    <logger name="com.app.ged.api.service" additivity="false" level="debug">
      <appender-ref ref="STDOUT"/>
      <appender-ref ref="SAVE-TO-FILE"/>
    </logger>
  </springProfile>

这篇关于如何使用Spring AOP和SPring引导进行日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆