码迷,mamicode.com
首页 > 编程语言 > 详细

springBoot AOP环绕增强、自定义注解、log4j2、MDC

时间:2018-11-19 22:40:23      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:signature   ddr   and   style   depend   控制   join   log   标识   

(一)log4j2 maven配置

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!-- 切换log4j2日志读取 -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
 <!-- 配置 log4j2 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <!-- 加上这个才能辨认到log4j2.yml文件 -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
        </dependency>

在resources 文件夹下创建log4j2.yml 文件

Configuration:
  status: warn
  Properties: # 定义全局变量
    Property: # 缺省配置(用于开发环境)。其他环境需要在VM参数中指定,如下:
      #测试:-Dlog.level.console=warn -Dlog.level.xjj=trace
      #生产:-Dlog.level.console=warn -Dlog.level.xjj=info
      - name: log.level.console
        value: trace
      - name: log.level.xjj
        value: trace
      - name: log.path
        value: D:/Logs/log
      - name: project.name
        value: my-spring-boot
  Appenders:
    Console:  #输出到控制台
      name: CONSOLE
      target: SYSTEM_OUT
      ThresholdFilter:
        level: ${sys:log.level.console} # “sys:”表示:如果VM参数中没指定这个变量值,则使用本文件中定义的缺省全局变量值
        onMatch: ACCEPT
        onMismatch: DENY
      PatternLayout:
        pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m %X{REQUESTID} %n"
    RollingFile: # 输出到文件,超过128MB归档
      - name: ROLLING_FILE
        ignoreExceptions: false
        fileName: ${log.path}/${project.name}.log
        filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
        PatternLayout:
          pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m %X{REQUESTID} %n"
        Policies:
          SizeBasedTriggeringPolicy:
            size: "128 MB"
        DefaultRolloverStrategy:
          max: 1000
  Loggers:
    Root:
      level: info
      AppenderRef:
        - ref: CONSOLE
        - ref: ROLLING_FILE
    Logger: # 为com.xjj包配置特殊的Log级别,方便调试
      - name: com.xjj
        additivity: false
        level: ${sys:log.level.xjj}
        AppenderRef:
          - ref: CONSOLE
          - ref: ROLLING_FILE

其中 %X{REQUESTID} 为MDC设定的请求标识,每个请求都会有,用于跟踪日志。

(二)MDC和AOP 环绕增强、自定义注解

创建日志类

public class tools_log {
    public static Logger getLogger(Class class_) {
        Logger logger = LoggerFactory.getLogger(class_);
        return logger;
    }
}//end

AOP、MDC

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Pointcut("execution(public * 包路径..*.*(..))")
    public void LogHelp() {
    }

    @Pointcut("@annotation(自定义注解路径)")
    public void noAnnotation() {
    }

    final Logger logger = tools_log.getLogger(this.getClass());

    @Around("LogHelp()&&!noAnnotation()")
    public Object arround(ProceedingJoinPoint joinPoint) {
        MDC.put("REQUESTID", UUID.randomUUID().toString());
        logger.info("方法环绕start.....");
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + JSON.toJSONString(joinPoint.getArgs()));
        try {
            Object o = joinPoint.proceed();
            logger.info("方法环绕proceed,结果是 :" + o);
            return o;
        } catch (Throwable e) {
            logger.error(e.toString());
            return null;
        } finally {
            MDC.clear();
        }
    }
}//end

.. 表示匹配多个参数

*  表示匹配一个参数

.* 表示匹配多个类

 

自定义注解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface noAroundAnno {
}//end

定义在方法上

 

springBoot AOP环绕增强、自定义注解、log4j2、MDC

标签:signature   ddr   and   style   depend   控制   join   log   标识   

原文地址:https://www.cnblogs.com/hcfan/p/9986185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!