Spring Boot 具有千分尺跟踪的Sping Boot 3 Webflux应用程序未在控制台日志中显示traceId和spanId

6vl6ewon  于 2022-12-04  发布在  Spring
关注(0)|答案(1)|浏览(188)

我正在替换Spring Cloud Sleuth,以便使用新的Micrometer Tracing for Sping Boot 3生成日志关联。
我一直在跟踪this blog post以配置sample project
traceId/spanId似乎不是针对每个请求自动生成的:

@GetMapping("/hello")
    fun hello(): String {
        val currentSpan: Span? = tracer.currentSpan()
        logger.info("Hello!")
        return "hello"
    }

currentSpan为空,日志显示空字符串:

2022-11-28T14:53:05.335+01:00  INFO [server,,] 9176 --- [ctor-http-nio-2] d.DemotracingApplication$$SpringCGLIB$$0 : Hello!

这是我当前的配置:

logging.pattern.level=%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]

和依赖关系:

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-actuator")
    implementation("org.springframework.boot:spring-boot-starter-webflux")
    implementation("org.springframework.boot:spring-boot-starter-aop")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("io.micrometer:micrometer-tracing-bridge-brave")
    implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
    implementation("io.micrometer:micrometer-registry-prometheus")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("io.projectreactor:reactor-test")
}

为什么不管用?

编辑:

WebMVC应用程序不受此问题的影响,并在升级后记录相关信息。
不过Webflux应用程序的行为似乎有了变化,有和open issue about this

2w2cym1i

2w2cym1i1#

有几种方法可以实现它,下面的摘录显示了其中的两种,ContextSnapshot.setThreadLocalsFromhandle()运算符

@GetMapping("/hello")
    fun hello(): Mono<String> {
        return Mono.deferContextual { contextView: ContextView ->
            ContextSnapshot.setThreadLocalsFrom(contextView, ObservationThreadLocalAccessor.KEY)
                .use { scope: ContextSnapshot.Scope ->
                    val traceId = tracer.currentSpan()!!.context().traceId()
                    logger.info("<ACCEPTANCE_TEST> <TRACE:{}> Hello!", traceId)
                    webClient.get().uri("http://localhost:7654/helloWc")
                        .retrieve()
                        .bodyToMono(String::class.java)
                        .handle { t: String, u: SynchronousSink<String> ->
                            logger.info("Retrieved helloWc {}", t)
                            u.next(t)
                        }
                }
        }
    }

相关问题