【Java】日志输出自定义变量值

背景

  Java打印日志时,输出自定义变量值(以logback为例)

 

步骤

1. 删除引入的基础配置类(如无则忽略)

<include resource="org/springframework/boot/logging/logback/base.xml"/>
 

2. 添加配置信息

traceId为自定义变量名,%X{traceId}必须都包含

<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">

<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>%X{traceId} %d{HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg</pattern> <charset>utf-8</charset> </encoder> </appender>

<root LEVEL="info"> <appender-ref ref="Console"/> </root>

 

3. 代码中给自定义变量赋值 

org.slf4j.MDC.put("traceId", UUID.randomUUID().toString()); log.info("test");

 

posted @ 2021-02-07 10:53    阅读(505)  评论(0编辑  收藏  举报