Skip to content

Custom trace‐id in YARP

Thang Chung edited this page Sep 30, 2024 · 1 revision

Adding code for transforming and replacing trace-id on gateway

builder.Services.AddReverseProxy()
				.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
				.AddTransforms(b =>
				{
					// todo: only for testing purposes, remove later
					// https://stackoverflow.com/questions/70306118/set-traceid-on-activity
					b.AddRequestTransform(async transformContext =>
					{
						var context = transformContext.HttpContext;
						var traceIdFromProxy = context.Request.Headers["trace-id"].FirstOrDefault()?.Trim('"');
						if (Guid.TryParse(traceIdFromProxy, out var parsedGuid))
						{
							traceIdFromProxy = parsedGuid.ToString("N");
						}
						else
						{
							// Handle the case where the traceId is not a valid GUID
							traceIdFromProxy = Guid.NewGuid().ToString("N");
						}

						if (context.Request.Headers.TryGetValue("traceparent", out var traceParent))
						{
							if (context.Request.Headers.Remove("traceparent"))
							{
								var traceParentReplaced = Regex.Replace(traceParent, "-.*?-", $"-${traceIdFromProxy}-");
								Activity.Current = new Activity("Yarp.ReverseProxy")
									.SetParentId(traceParentReplaced)
									.Start();
							}
						}

						await ValueTask.CompletedTask;
					});
				})
				.AddServiceDiscoveryDestinationResolver();

Submitting the request with a trace header

###
GET http://{{hostname}}/p/api/v1/item-types
content-type: application/json
trace-id: "{{$guid}}"