1+ using Microsoft . AspNetCore . Diagnostics . HealthChecks ;
2+ using Microsoft . Extensions . Diagnostics . HealthChecks ;
3+ using OpenTelemetry ;
4+ using OpenTelemetry . Metrics ;
5+ using OpenTelemetry . Trace ;
6+ using TodosApi ;
7+
8+ namespace Microsoft . Extensions . Hosting ;
9+
10+ public static class Extensions
11+ {
12+ public static IHostApplicationBuilder AddServiceDefaults ( this IHostApplicationBuilder builder )
13+ {
14+ builder . ConfigureOpenTelemetry ( ) ;
15+
16+ builder . AddDefaultHealthChecks ( ) ;
17+
18+ return builder ;
19+ }
20+
21+ public static IHostApplicationBuilder ConfigureOpenTelemetry ( this IHostApplicationBuilder builder )
22+ {
23+ builder . Logging . AddOpenTelemetry ( logging =>
24+ {
25+ logging . IncludeFormattedMessage = true ;
26+ logging . IncludeScopes = true ;
27+ } ) ;
28+
29+ builder . Services . AddOpenTelemetry ( )
30+ . WithMetrics ( metrics =>
31+ {
32+ metrics . AddAspNetCoreInstrumentation ( )
33+ . AddHttpClientInstrumentation ( )
34+ . AddRuntimeInstrumentation ( ) ;
35+ } )
36+ . WithTracing ( tracing =>
37+ {
38+ tracing . AddAspNetCoreInstrumentation ( )
39+ . AddHttpClientInstrumentation ( ) ;
40+ } ) ;
41+
42+ builder . AddOpenTelemetryExporters ( ) ;
43+
44+ return builder ;
45+ }
46+
47+ private static IHostApplicationBuilder AddOpenTelemetryExporters ( this IHostApplicationBuilder builder )
48+ {
49+ var useOtlpExporter = ! string . IsNullOrWhiteSpace ( builder . Configuration [ "OTEL_EXPORTER_OTLP_ENDPOINT" ] ) ;
50+
51+ if ( useOtlpExporter )
52+ {
53+ builder . Services . AddOpenTelemetry ( ) . UseOtlpExporter ( ) ;
54+ }
55+
56+ return builder ;
57+ }
58+
59+ public static IHostApplicationBuilder AddDefaultHealthChecks ( this IHostApplicationBuilder builder )
60+ {
61+ builder . Services . AddHealthChecks ( )
62+ // Add a default liveness check to ensure app is responsive
63+ . AddCheck ( "self" , ( ) => HealthCheckResult . Healthy ( ) , [ "live" ] )
64+ . AddCheck < DatabaseHealthCheck > ( "Database" , timeout : TimeSpan . FromSeconds ( 2 ) )
65+ . AddCheck < JwtHealthCheck > ( "JwtAuthentication" ) ;
66+
67+ return builder ;
68+ }
69+
70+ public static WebApplication MapDefaultEndpoints ( this WebApplication app )
71+ {
72+ // Adding health checks endpoints to applications in non-development environments has security implications.
73+ // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments.
74+ if ( app . Environment . IsDevelopment ( ) )
75+ {
76+ // All health checks must pass for app to be considered ready to accept traffic after starting
77+ app . MapHealthChecks ( "/health" ) ;
78+
79+ // Only health checks tagged with the "live" tag must pass for app to be considered alive
80+ app . MapHealthChecks ( "/alive" , new HealthCheckOptions
81+ {
82+ Predicate = r => r . Tags . Contains ( "live" )
83+ } ) ;
84+ }
85+
86+ return app ;
87+ }
88+ }
0 commit comments