在日志中添加了 MDC,以便能够在 Stackdriver 仪表板和日志控制台中跟踪特定错误日志。当前的实现在本地机器上运行良好,但在云上却不是——只是不要将我的 MDC 包括在日志条目中。问题是我根本无法弄清楚可能是什么问题。
本地日志输出(包含“contextKey”:“someValue”):
{"traceId":"615b35dc7f639027","spanId":"615b35dc7f639027","spanExportable":"false","contextKey":"someValue","timestampSeconds":1552311117,"timestampNanos":665000000,"severity":"ERROR","thread":"reactor-http-nio-3","logger":"com.example.someservice.controller.MyController", ...}
同一服务的 Kubernetes 容器日志(此日志条目中没有“contextKey”:“someValue”):
{"traceId":"8d7287fa0ebdacfce9b88097e290ecbf","spanId":"96967afbe05dbf0e","spanExportable":"false","X-B3-ParentSpanId":"224dcb9869488858","parentId":"224dcb9869488858","timestampSeconds":1552312549,"timestampNanos":752000000,"severity":"ERROR","thread":"reactor-http-epoll-2","logger":"com.example.someservice.controller.MyController","message":"Something went wrong","context":"default","logging.googleapis.com/trace":"projects/my-project/traces/8d7287fa0ebdacfce9b88097e290ecbf","logging.googleapis.com/spanId":"96967afbe05dbf0e"}
我的 logback.xml:
<configuration>
<appender name="CONSOLE_JSON" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="org.springframework.cloud.gcp.autoconfigure.logging.StackdriverJsonLayout">
<projectId>${projectId}</projectId>
</layout>
</encoder>
</appender>
<springProfile name="local,dev,test">
<root level="INFO">
<appender-ref ref="CONSOLE_JSON"/>
</root>
</springProfile>
</configuration>
使用定义的 MDC 触发日志创建的控制器:
@RestController
@RequestMapping("v1/my-way")
@Slf4j
public class MyController {
@GetMapping
public void read() {
MDC.put("contextKey", "someValue");
log.error("Something went wrong");
MDC.remove("contextKey")
}
}