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
- Detail
-
Ant Group Powers the Greater Bay Area's "One-Hour Living Circle" and Fuels Global "ChinaTravel Boom"Detail
2024-11-21 19:23:04 1
-
Shenzhen's First Roadside Supercharger Station Commences Trial Operation, Ushering in a New Era for the "Supercharging City"Detail
2024-11-21 11:25:06 1
-
Xiaomi's High-End Strategy: An In-Depth Analysis of Q3 2024 Financial Results and Future OutlookDetail
2024-11-19 23:07:40 1
-
TSMC's Sudden Shift: A Global Chip Giant's Difficult Choices in the US-China GameDetail
2024-11-19 12:27:48 1
-
International Space Station Leak Crisis: NASA's Emergency Evacuation Plan and Signals of Chinese CooperationDetail
2024-11-19 11:34:51 1
-
Ten Years of Searching: Li Eryou's Unwavering Hope in the Search for His Son on MH370Detail
2024-11-18 18:39:16 1
-
The Facial Swelling of Shenzhou 18 Astronauts: The Physiological Cost of Space Exploration and Future ChallengesDetail
2024-11-17 08:03:04 11
-
Xiaomi Automobile Unveils Intelligent Chassis Pre-Research Technology, Ushering in a New Era of "Human-Car-Home Full Ecosystem"Detail
2024-11-14 11:24:27 1
-
Douyin E-commerce Double 11 Data Report: Merchants Businesses Grow, Consumer Trends EmergeDetail
2024-11-14 11:23:11 1
-
New Trends in SOE Reform: Focusing on Five Values to Build a "Living Organism"Detail
2024-11-14 11:19:26 1
-
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 11
-
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