|
| 1 | +using Microsoft.Extensions.DependencyInjection; |
| 2 | +using Microsoft.Extensions.Hosting; |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | +using OpenTelemetry.Logs; |
| 5 | +using OpenTelemetry.Metrics; |
| 6 | +using OpenTelemetry.Trace; |
| 7 | + |
| 8 | +namespace TeamUp.Infrastructure; |
| 9 | + |
| 10 | +public static class HostApplicationBuilderExtensions |
| 11 | +{ |
| 12 | + public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder) |
| 13 | + { |
| 14 | + builder.Logging.AddOpenTelemetry(options => |
| 15 | + { |
| 16 | + options.IncludeScopes = true; |
| 17 | + options.IncludeFormattedMessage = true; |
| 18 | + }); |
| 19 | + |
| 20 | + builder.Services |
| 21 | + .AddOpenTelemetry() |
| 22 | + .WithMetrics(metrics => |
| 23 | + { |
| 24 | + metrics.AddAspNetCoreInstrumentation(); |
| 25 | + metrics.AddHttpClientInstrumentation(); |
| 26 | + metrics.AddRuntimeInstrumentation(); |
| 27 | + |
| 28 | + metrics.AddPrometheusExporter(); |
| 29 | + }) |
| 30 | + .WithTracing(tracing => |
| 31 | + { |
| 32 | + if (builder.Environment.IsDevelopment()) |
| 33 | + { |
| 34 | + tracing.SetSampler<AlwaysOnSampler>(); |
| 35 | + } |
| 36 | + |
| 37 | + tracing.AddSource(builder.Environment.ApplicationName); |
| 38 | + tracing.AddAspNetCoreInstrumentation(); |
| 39 | + tracing.AddHttpClientInstrumentation(); |
| 40 | + }); |
| 41 | + |
| 42 | + var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); |
| 43 | + if (useOtlpExporter) |
| 44 | + { |
| 45 | + builder.Services.Configure<OpenTelemetryLoggerOptions>(options => options.AddOtlpExporter()); |
| 46 | + builder.Services.ConfigureOpenTelemetryMeterProvider(options => options.AddOtlpExporter()); |
| 47 | + builder.Services.ConfigureOpenTelemetryTracerProvider(options => options.AddOtlpExporter()); |
| 48 | + } |
| 49 | + |
| 50 | + return builder; |
| 51 | + } |
| 52 | +} |
0 commit comments