结构化Stackdriver日志-将MDC添加到日志

时间:2019-03-07 15:49:21

标签: spring-boot google-cloud-platform google-cloud-stackdriver spring-cloud-gcp

在日志中添加了MDC,以便能够跟踪Stackdriver Dashboard和Logging Console中的特定错误日志。当前的实现在本地计算机上运行良好,但在云上却不行-只是不包括我的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")
    }

}

1 个答案:

答案 0 :(得分:0)

您的MDC字段应该在日志实体的“标签”节点上可用。你检查了吗?

还可以在Logs Viewer的Google Console中设置MDC字段以显示在日志记录中。为此,请在“视图选项”->“修改自定义字段”(位于屏幕右上方)中设置“ labels.YouCustomMDCField:

更新:但是,使用与我不同的方法登录到Stackdriver。我正在使用

<appender name="STACKDRIVER" class="com.google.cloud.logging.logback.LoggingAppender">
    <log>
        ${log_file_name}
    </log>
</appender>

就可以了(我也有Spring)。