Home Page >  News List >> Tech >> Tech

Log printing traceId when using Skywalking on SpringCloudGateway

Tech 2023-07-18 00:47:52 Source: Network
AD

SpringCloudGateway3.1

SpringCloudGateway3.1.3 SkywalkingAgent8.10.0 Agent SpringCloudGatewayWebFluxskywalkingagentoptional-pluginsjarplugins apm-spring-webflux-5.x-plugin-8.10.0.jar apm-spring-cloud-gateway-3.x-plugin-8.10.0.jar Maven < dependency > < groupId > org.apache.skywalking </ groupId > < artifactId > apm-toolkit-log4j-2.x </ artifactId > < version > ${skywalking.version} </ version > </ dependency > < dependency > < groupId > org.apache.skywalking </ groupId > < artifactId > apm-toolkit-trace </ artifactId > < version > ${skywalking.version} </ version > </ dependency > pattern [%d{yyyy-MM-ddHH:mm:ss.SSS}][%traceId][%logger {36} ][%thread][%- 5 level]%msg%n -javaagent:D:workskywalking-agentskywalking-agent.jar=agent.service_name=xxx -Dskywalking.collector.backend_service=xxx:11800 Skywalking-ui TID [ 2022 -06 -15 14 : 53 : 19.958 ][TID:N/A] agent Skywalking-agent apm-spring-webflux-5.x-plugin-8.10.0.jar org.springframework.web.reactive.DispatcherHandler handle reactor< SKYWALKING_CONTEXT_SNAPSHOT-ContextSnapshot> traceIdreactorcontext traceId public static<T>Consumer<Signal<T>>logOnNext(Consumer<T>logStatement){ return signal->{ if (!signal.isOnNext()) return ;( 1 )Optional<String>toPutInMdc=signal.getContext().getOrEmpty( "CONTEXT_KEY" );( 2 )toPutInMdc.ifPresentOrElse(tpim->{ try (MDC.MDCCloseablecMdc=MDC.putCloseable( "MDC_KEY" ,tpim)){( 3 )logStatement.accept(signal. get ());( 4 )}},()->logStatement.accept(signal. get ()));( 5 )};} @GetMapping( "/byPrice" ) public Flux<Restaurant>byPrice( @RequestParam Double maxPrice, @RequestHeader(required=false,name= "X-UserId" ) StringuserId){StringapiId=userId== null ? "" :userId;( 1 ) return restaurantService.byPrice(maxPrice)).doOnEach(logOnNext(r->LOG.debug( "foundrestaurant{}for ${} " ,( 2 )r.getName(),r.getPricePerPerson()))).contextWrite(Context.of( "CONTEXT_KEY" ,apiId));( 3 )} traceId equals{pattern}{ test }{substitution}equalsIgnoreCase{pattern}{ test }{substitution} pattern [%d{yyyy-MM-ddHH:mm:ss.SSS}][TID:%equals{%X{traceId}}{}{N/A}][%logger{36}][%thread][%-5level]%msg%n onEachOperatorHooks @Component public class LogHooks { private static final StringKEY= "logMdc" ; @PostConstruct @SuppressWarnings ( "unchecked" ) public void setHook () {reactor.core.publisher.Hooks.onEachOperator(KEY,Operators.lift((scannable,coreSubscriber)-> new MdcSubscriber(coreSubscriber)));} @PreDestroy public void resetHook () {reactor.core.publisher.Hooks.resetOnEachOperator(KEY);}} public class MdcSubscriber implements CoreSubscriber { private static final StringTRACE_ID= "traceId" ; private static final StringSKYWALKING_CTX_SNAPSHOT= "SKYWALKING_CONTEXT_SNAPSHOT" ; private final CoreSubscriber<Object> actual ; public MdcSubscriber(CoreSubscriber<Object> actual ){ this . actual = actual ;} @Override public voidonSubscribe(Subscriptions){ actual .onSubscribe(s);} @Override public voidonNext(Objecto){Contextc= actual .currentContext();Optional<String>traceIdOptional=Optional.empty(); if (!c.isEmpty()&&c.hasKey(SKYWALKING_CTX_SNAPSHOT)){traceIdOptional=Optional.of(c. get (SKYWALKING_CTX_SNAPSHOT)).map(BeanUtil::beanToMap).map(t->t. get (TRACE_ID)).map(BeanUtil::beanToMap).map(t->t. get ( "id" )).map(Object::toString);} try (MDC.MDCCloseablecMdc=MDC.putCloseable(TRACE_ID,traceIdOptional.orElse( "N/A" ))){ actual .onNext(o);}} @Override public voidonError(Throwablethrowable){ actual .onError(throwable);} @Override public voidonComplete(){ actual .onComplete();} @Override public ContextcurrentContext(){ return actual .currentContext();}}

Disclaimer: The content of this article is sourced from the internet. The copyright of the text, images, and other materials belongs to the original author. The platform reprints the materials for the purpose of conveying more information. The content of the article is for reference and learning only, and should not be used for commercial purposes. If it infringes on your legitimate rights and interests, please contact us promptly and we will handle it as soon as possible! We respect copyright and are committed to protecting it. Thank you for sharing.(Email:[email protected])

Mobile advertising space rental

Tag: Log printing traceId when using Skywalking on SpringCloudGateway

Unite directoryCopyright @ 2011-2024 All Rights Reserved. Copyright Webmaster Search Directory System