From 5ea63f6f8cf4e4181fcbc3074f80ec227afdcbfd Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Fri, 8 Oct 2021 10:53:15 +0200 Subject: [PATCH] Adding span flushing on shutdown hook (#2036) without this change when batch process finishes the async reporter doesn't have time to properly shutdown and send out spans to Zipkin. with this change we're registering a shutdown hook. AsyncReporter has no option to send out spans in a blocking way, so what we need to do to flush it, then wait for the configured time for the spans to be drained from the queue and then give a chance to send the spans out over the wire. fixes gh-2035 --- .../zipkin2/ZipkinAutoConfiguration.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/spring-cloud-sleuth-autoconfigure/src/main/java/org/springframework/cloud/sleuth/autoconfig/zipkin2/ZipkinAutoConfiguration.java b/spring-cloud-sleuth-autoconfigure/src/main/java/org/springframework/cloud/sleuth/autoconfig/zipkin2/ZipkinAutoConfiguration.java index 1b1559997..6afb46530 100644 --- a/spring-cloud-sleuth-autoconfigure/src/main/java/org/springframework/cloud/sleuth/autoconfig/zipkin2/ZipkinAutoConfiguration.java +++ b/spring-cloud-sleuth-autoconfigure/src/main/java/org/springframework/cloud/sleuth/autoconfig/zipkin2/ZipkinAutoConfiguration.java @@ -135,6 +135,22 @@ public class ZipkinAutoConfiguration { .messageTimeout(zipkin.getMessageTimeout(), TimeUnit.SECONDS).metrics(reporterMetrics) .build(zipkin.getEncoder()); + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + log.info("Flushing remaining spans on shutdown"); + asyncReporter.flush(); + try { + Thread.sleep(TimeUnit.SECONDS.toMillis(zipkin.getMessageTimeout()) + 500); + log.debug("Flushing done - closing the reporter"); + asyncReporter.close(); + } + catch (Exception e) { + throw new IllegalStateException(e); + } + } + }); + return asyncReporter; }