| | | 1 | | using System.Reflection; |
| | | 2 | | using System.Security.Claims; |
| | | 3 | | using OpenTelemetry.Logs; |
| | | 4 | | using OpenTelemetry.Metrics; |
| | | 5 | | using OpenTelemetry.Resources; |
| | | 6 | | using OpenTelemetry.Trace; |
| | | 7 | | |
| | | 8 | | namespace ClutterStock.Api.Extensions; |
| | | 9 | | |
| | | 10 | | internal static class OpenTelemetryServiceExtensions |
| | | 11 | | { |
| | | 12 | | public static IServiceCollection AddOpenTelemetryObservability(this IServiceCollection services, |
| | | 13 | | IHostEnvironment environment) |
| | | 14 | | { |
| | 3 | 15 | | var serviceVersion = Assembly.GetExecutingAssembly() |
| | 3 | 16 | | .GetName() |
| | 3 | 17 | | .Version?.ToString(); |
| | | 18 | | |
| | 3 | 19 | | services.AddOpenTelemetry() |
| | 3 | 20 | | .ConfigureResource(resource => resource.AddService( |
| | 3 | 21 | | environment.ApplicationName, |
| | 3 | 22 | | serviceVersion: serviceVersion)) |
| | 3 | 23 | | .WithTracing(static tracing => tracing |
| | 3 | 24 | | .AddAspNetCoreInstrumentation(static options => |
| | 3 | 25 | | { |
| | 3 | 26 | | options.RecordException = true; |
| | 3 | 27 | | options.Filter = static ctx => |
| | 3 | 28 | | !ctx.Request.Path.StartsWithSegments("/healthz"); |
| | 3 | 29 | | options.EnrichWithHttpResponse = static (activity, response) => |
| | 3 | 30 | | { |
| | 3 | 31 | | var user = response.HttpContext.User; |
| | 3 | 32 | | if (user.Identity?.IsAuthenticated != true) |
| | 3 | 33 | | return; |
| | 3 | 34 | | |
| | 3 | 35 | | var userId = user.FindFirstValue("sub") |
| | 3 | 36 | | ?? user.FindFirstValue(ClaimTypes.NameIdentifier); |
| | 3 | 37 | | if (!string.IsNullOrEmpty(userId)) |
| | 3 | 38 | | activity.SetTag("enduser.id", userId); |
| | 3 | 39 | | }; |
| | 3 | 40 | | }) |
| | 3 | 41 | | .AddHttpClientInstrumentation(static options => options.RecordException = |
| | 3 | 42 | | .AddEntityFrameworkCoreInstrumentation() |
| | 3 | 43 | | .AddOtlpExporter()) |
| | 3 | 44 | | .WithMetrics(static metrics => metrics |
| | 3 | 45 | | .AddAspNetCoreInstrumentation() |
| | 3 | 46 | | .AddRuntimeInstrumentation() |
| | 3 | 47 | | .AddOtlpExporter()) |
| | 3 | 48 | | .WithLogging(static logging => logging |
| | 3 | 49 | | .AddOtlpExporter()); |
| | | 50 | | |
| | 3 | 51 | | return services; |
| | | 52 | | } |
| | | 53 | | } |