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
-
Poland: An Emerging Market for Chinese Cross-border E-commerce, Cainiao Overseas Warehouses Fuel Explosive GrowthDetail
2025-01-21 11:06:16 1
-
The Central Political and Legal Affairs Work Conference Focuses on Autonomous Driving Legislation: Fast-Tracking Industry DevelopmentDetail
2025-01-20 16:41:45 1
-
The SHEIN Foundation Officially Launches: Partnering with ACT to Drive Textile Recycling and Sustainable Development in AfricaDetail
2025-01-20 15:21:39 1
-
BCIGroup Launches New Brand: Qineng Technology, Focusing on Next-Generation Infrastructure ConstructionDetail
2025-01-20 15:00:24 1
-
The Trump administration's potential TikTok ban could trigger a global domino effect: Lessons from the Kaspersky caseDetail
2025-01-20 08:42:29 1
-
China Leads in Developing IEC 63206 International Standard, Driving Global Innovation in Industrial Process Control System RecordersDetail
2025-01-18 11:06:14 1
-
The 2024 Micro-Short Series Industry Ecological Insight Report: 647,000 Job Opportunities, Rise of Diversified Business Models, and High-Quality Content as the Future TrendDetail
2025-01-17 17:33:01 1
-
Global PC Market Shows Moderate Recovery in 2024: High AIPC Prices a Bottleneck, Huge Growth Potential in 2025Detail
2025-01-17 11:02:09 1
-
Bosch's Smart Cockpit Platform Surpasses 2 Million Units Shipped, Showcasing Strength in Intelligent Driving TechnologyDetail
2025-01-17 10:55:29 1
-
YY Guangzhou Awarded "2024 Network Information Security Support Unit" for Outstanding ContributionsDetail
2025-01-17 10:43:28 1
-
TikTok CEO Invited to Trump's Inauguration, Biden Administration May Delay BanDetail
2025-01-16 20:06:11 1
-
Douyin Denies Opening International Registration: Overseas IPs Don't Equate to Overseas Registration; Platform Actively Combats Account ImpersonationDetail
2025-01-16 14:26:12 1
-
Lei Jun, Xiaomi's founder, chairman, and CEO, has set a new goal: learning to drive a forklift!Detail
2025-01-15 10:22:30 11
-
ByteDance Scholarship 2024: Fifteen Outstanding Doctoral Students Awarded RMB 100,000 Each to Advance Frontier Technology ExplorationDetail
2025-01-14 15:56:39 1
-
Fliggy Launches "Peace of Mind for the New Year" Service Initiative to Ensure Smooth Travel During the Year of the Snake Spring Festival RushDetail
2025-01-14 15:24:53 1
-
Arm's Massive Fee Hike and Potential In-House Chip Development: A Precursor to a Seismic Shift in the Chip Industry?Detail
2025-01-14 11:02:36 1
-
Adobe Firefly Launches: Generative AI Suite Revolutionizes Image and Video Processing EfficiencyDetail
2025-01-14 10:46:39 1
-
Chinese New Year Elements Sell Like Hotcakes Overseas: Cross-border E-commerce "Spring Festival Economy" Booms, Cainiao Overseas Warehouses Help Merchants Capture Market ShareDetail
2025-01-13 14:17:50 1
-
China Railway's 12306 System Successfully Navigates Spring Festival Travel RushDetail
2025-01-13 12:56:54 1
-
Handan, Hebei Province Successfully Tests First Low-Altitude Drone Delivery Route, Ushering in a New Era of Smart LogisticsDetail
2025-01-13 12:50:13 1