首页 > 解决方案 > 如何使用 Spring Boot 的应用程序日志(由 slf4j 生成)丰富 Jaeger opentracing 数据?

问题描述

有一个使用 SLF4J 记录器的现有 Spring Boot 应用程序。我决定opentracing使用 Jaeger 作为跟踪器,通过标准 API 添加对分布式跟踪的支持。初始设置如此简单真是令人惊讶 - 所需要的只是将两个依赖项添加到pom.xml

    <dependency>
        <groupId>io.opentracing.contrib</groupId>
        <artifactId>opentracing-spring-web-autoconfigure</artifactId>
        <version>${io.opentracing.version}</version>
    </dependency>

    <dependency>
        <groupId>io.jaegertracing</groupId>
        <artifactId>jaeger-core</artifactId>
        <version>${jaegerVersion}</version>
    </dependency>

并为Tracerbean 提供配置:

@Bean
public io.opentracing.Tracer getTracer() throws ConfigurationException {
    return new new io.jaegertracing.Tracer.Builder("my-spring-boot-app").build();
}

所有的工作都像一个魅力 - 应用程序请求由 Jaeger 处理并创建跨度:

在此处输入图像描述

但是,在跨度Logs中,只有preHandle&afterCompletion事件包含有关在请求执行期间调用的类/方法的信息(不slf4j收集记录器生成的日志):

在此处输入图像描述

问题是是否可以将 Tracer 配置为拾取应用程序记录器(slf4j在我的情况下)生成的日志,以便通过://etc. 完成的所有应用程序日志LOG.infoLOG.warnLOG.error反映在 Jaeger 中

注意:我已经想出了如何通过API手动记录跨度,例如:opentracing

Scope scope = tracer.scopeManager().active();
if (scope != null) {
    scope.span().log("...");
}

并使用标签对过滤器中的异常处理进行一些手动操作,例如ERROR

} catch(Exception ex) {
    Tags.ERROR.set(span, true);
    span.log(Map.of(Fields.EVENT, "error", Fields.ERROR_OBJECT, ex, Fields.MESSAGE, ex.getMessage()));
    throw ex
}

但是,我仍然想知道是否可以配置跟踪器来获取应用程序日志automatically

更新:我能够通过为记录器添加包装器来将应用程序日志添加到跟踪器,例如

public void error(String message, Exception e) {
    Scope scope = tracer.scopeManager().active();
    if (scope != null) {
        Span span = scope.span();
        Tags.ERROR.set(span, true);
        span.log(Map.of(Fields.EVENT, "error", Fields.ERROR_OBJECT, e, Fields.MESSAGE, e.getMessage()));

    }
    LOG.error(message, e);
}

但是,到目前为止,我还没有找到默认情况下允许将应用程序日志自动添加到跟踪器的 opentracing 配置选项。基本上,如果需要,似乎预计开发人员会以编程方式将额外的日志添加到跟踪器。另外,在调查了更多跟踪之后,它似乎是正常的logging并且tracing是单独处理的,并且将所有应用程序日志添加到跟踪器不是一个好主意(跟踪器应该主要包括示例数据和用于请求识别的标签)

标签: spring-bootloggingslf4jopentracingjaeger

解决方案


https://github.com/opentracing-contrib/java-spring-cloud项目自动将标准日志发送到活动跨度。只需将以下依赖项添加到您的 pom.xml

<dependency>
   <groupId>io.opentracing.contrib</groupId>
   <artifactId>opentracing-spring-cloud-starter</artifactId>
</dependency>

如果您只想集成日志记录,或者使用此https://github.com/opentracing-contrib/java-spring-cloud/tree/master/instrument-starters/opentracing-spring-cloud-core starter。


推荐阅读