Log printing traceId when using Skywalking on SpringCloudGateway
AD |
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();}}SpringCloudGateway3.1
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
400 pilots collectively switch jobs in China, vowing never to return home and vowing to "serve" China?
NextPressure Test Report on Elasticsearch with Different Slice Settings
Guess you like
-
CATL Chairman Zeng Yuqun: Musk Doesn't Understand Batteries, Tesla's Bet on Cylindrical Batteries is Doomed to FailDetail
2024-11-13 18:47:38 1
-
China Eastern Airlines Technology and Thales Renew Cooperation Agreement, Deepening Avionics Maintenance PartnershipDetail
2024-11-13 16:40:50 1
- Detail
- Detail
- Detail
-
Li Jiaqi's Livestream Double 11 Report: Domestic Brands Surge, Winter Warmer Economy BoomsDetail
2024-11-12 11:07:26 11
-
BYD: Plug-in Hybrids "To the Rescue," Behind the Price War Lies a "Davis Double-Click" in ProfitabilityDetail
2024-11-12 10:49:05 1
-
The Rise of Online Livestreamers: A Mass Career with 15 Million Dream Chasers in Live RoomsDetail
2024-11-11 15:27:33 11
-
Microsoft "Mail and Calendar" app will be officially discontinued at the end of next year, users need to migrate to the new OutlookDetail
2024-11-10 14:53:36 11
- Detail
-
Alibaba Pictures' Phoenix Cloud Intelligence International Edition iCIRENA Expands to Hong Kong and Macau, Bringing Technological Upgrades to CinemasDetail
2024-11-09 11:22:49 1
-
From Daughter of Heaven to Ordinary Mom: Liu Yang's Space Dream and the Diversification of LifeDetail
2024-11-09 10:36:56 1
- Detail
-
Global Focus: CIIE Signs Deals Worth Over 10 Billion, 6G Technology Takes the Lead, Avian Flu Outbreak Ravages, Typhoon "Ginkgo" ApproachesDetail
2024-11-08 14:39:05 1
-
The Battle for the Smartphone Throne: Apple, Samsung, and Huawei Vie for DominanceDetail
2024-11-07 21:01:50 1
-
Why Chinese Astronauts Lie Down When Exiting the Capsule? The Truth is Not InferiorityDetail
2024-11-07 00:51:26 11
- Detail
-
CIIE: A Feast of Openness and Cooperation, A Shared Commitment of Global EnterprisesDetail
2024-11-06 18:51:38 11
-
Tencent's Palm Payment Technology Goes Global: Partnership with Visa Launches New Era of International Payments in SingaporeDetail
2024-11-06 17:38:54 31
-
The 6G Patent Race: A Trilateral Contest for Future Communication Network DominanceDetail
2024-11-06 15:35:53 11