mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 22:11:10 +00:00
Adds OpenTelemetry pipelines and health probes to the presentation layer
This commit is contained in:
1 parent
a2c99b1b79
commit
6af3d4f5e5
22 files changed
+800
-20
No files matched your search
@@ -3,6 +3,7 @@ using FastEndpoints;
|
||||
using FastEndpoints.Swagger;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Presentation.Api.Common.Authentication;
|
||||
using Lumina.Presentation.Api.Common.HealthChecks;
|
||||
using MessagePack;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
@@ -10,6 +11,7 @@ using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Json;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System;
|
||||
@@ -39,6 +41,10 @@ public static class PresentationApiLayerServices
|
||||
services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting
|
||||
services.AddProblemDetails();
|
||||
|
||||
// the readiness health check verifies that the database can be reached, and is probed by container orchestrators and load balancers
|
||||
services.AddHealthChecks()
|
||||
.AddCheck<DatabaseHealthCheck>("database", HealthStatus.Unhealthy, ["ready"]);
|
||||
|
||||
services.Configure<JsonOptions>(jsonOptions =>
|
||||
{
|
||||
jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Telemetry;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using OpenTelemetry;
|
||||
using OpenTelemetry.Metrics;
|
||||
using OpenTelemetry.Resources;
|
||||
using OpenTelemetry.Trace;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains the OpenTelemetry services of the Presentation API layer.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class PresentationApiTelemetryServices
|
||||
{
|
||||
private const string SERVICE_NAME = "Lumina.Api";
|
||||
private const string ENTITY_FRAMEWORK_CORE_METER_NAME = "Microsoft.EntityFrameworkCore";
|
||||
|
||||
/// <summary>
|
||||
/// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <param name="configuration">Application configuration properties.</param>
|
||||
/// <param name="environment">The hosting environment of the application.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddPresentationApiTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
|
||||
{
|
||||
bool isTelemetryEnabled = configuration.GetValue<bool?>("Telemetry:Enabled") ?? true;
|
||||
if (!isTelemetryEnabled)
|
||||
return services;
|
||||
|
||||
bool isConsoleExporterEnabled = configuration.GetValue<bool?>("Telemetry:ConsoleExporterEnabled") ?? environment.IsDevelopment();
|
||||
string? otlpEndpoint = GetOtlpEndpoint(configuration);
|
||||
double traceSampleRatio = configuration.GetValue<double?>("Telemetry:TraceSampleRatio") ?? 1.0;
|
||||
string serviceVersion = typeof(Program).Assembly.GetName().Version?.ToString() ?? "unknown";
|
||||
|
||||
services.AddOpenTelemetry()
|
||||
.ConfigureResource(resourceBuilder => resourceBuilder
|
||||
.AddService(serviceName: SERVICE_NAME, serviceVersion: serviceVersion)
|
||||
.AddEnvironmentVariableDetector()
|
||||
.AddAttributes(new Dictionary<string, object>
|
||||
{
|
||||
["deployment.environment"] = environment.EnvironmentName
|
||||
}))
|
||||
.WithTracing(tracingBuilder =>
|
||||
{
|
||||
tracingBuilder.SetSampler(CreateSampler(traceSampleRatio));
|
||||
tracingBuilder.AddSource(ApplicationTelemetry.SOURCE_NAME);
|
||||
tracingBuilder.AddAspNetCoreInstrumentation();
|
||||
if (isConsoleExporterEnabled)
|
||||
tracingBuilder.AddConsoleExporter();
|
||||
if (otlpEndpoint is not null)
|
||||
tracingBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint));
|
||||
})
|
||||
.WithMetrics(metricsBuilder =>
|
||||
{
|
||||
metricsBuilder.AddMeter(ApplicationTelemetry.SOURCE_NAME);
|
||||
metricsBuilder.AddMeter(ENTITY_FRAMEWORK_CORE_METER_NAME);
|
||||
metricsBuilder.AddAspNetCoreInstrumentation();
|
||||
metricsBuilder.AddRuntimeInstrumentation();
|
||||
if (isConsoleExporterEnabled)
|
||||
metricsBuilder.AddConsoleExporter();
|
||||
if (otlpEndpoint is not null)
|
||||
metricsBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint));
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the OTLP exporter endpoint from configuration, falling back to the standard <c>OTEL_EXPORTER_OTLP_ENDPOINT</c> environment variable.
|
||||
/// </summary>
|
||||
/// <param name="configuration">Application configuration properties.</param>
|
||||
/// <returns>The OTLP endpoint, or <see langword="null"/> when no endpoint is configured.</returns>
|
||||
private static string? GetOtlpEndpoint(IConfiguration configuration)
|
||||
{
|
||||
string? endpoint = configuration.GetValue<string?>("Telemetry:Otlp:Endpoint");
|
||||
if (string.IsNullOrWhiteSpace(endpoint))
|
||||
endpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT");
|
||||
return string.IsNullOrWhiteSpace(endpoint) ? null : endpoint;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the trace sampler used by the API, sampling every trace by default and honoring the configured ratio for production traffic.
|
||||
/// </summary>
|
||||
/// <param name="traceSampleRatio">The ratio of traces to sample, in the range of zero to one.</param>
|
||||
/// <returns>The configured trace sampler.</returns>
|
||||
private static Sampler CreateSampler(double traceSampleRatio)
|
||||
{
|
||||
return traceSampleRatio < 1.0
|
||||
? new ParentBasedSampler(new TraceIdRatioBasedSampler(traceSampleRatio))
|
||||
: new AlwaysOnSampler();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Common.HealthChecks;
|
||||
|
||||
/// <summary>
|
||||
/// Health check that verifies the database can be reached.
|
||||
/// </summary>
|
||||
public class DatabaseHealthCheck : IHealthCheck
|
||||
{
|
||||
private readonly LuminaDbContext _dbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DatabaseHealthCheck"/> class.
|
||||
/// </summary>
|
||||
/// <param name="dbContext">Injected database context.</param>
|
||||
public DatabaseHealthCheck(LuminaDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the database can be reached.
|
||||
/// </summary>
|
||||
/// <param name="context">The health check context.</param>
|
||||
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
|
||||
/// <returns>A task that represents the asynchronous operation, containing the health check result.</returns>
|
||||
public virtual async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
bool canConnect = await _dbContext.Database.CanConnectAsync(cancellationToken).ConfigureAwait(false);
|
||||
return canConnect
|
||||
? HealthCheckResult.Healthy()
|
||||
: HealthCheckResult.Unhealthy("The database is not reachable.");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
return HealthCheckResult.Unhealthy("The database is not reachable.", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,10 +31,17 @@
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="OpenTelemetry" Version="1.18.0" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.18.0" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.18.0" />
|
||||
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.18.0" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.18.0" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.18.0" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.16.20" />
|
||||
<PackageReference Include="Serilog" Version="4.4.0" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageReference Include="Serilog.Enrichers.AspnetcoreHttpcontext" Version="1.1.0" />
|
||||
<PackageReference Include="Serilog.Enrichers.Span" Version="3.1.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||
|
||||
@@ -12,11 +12,14 @@ using Lumina.Presentation.Api.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Api.Common.Middlewares;
|
||||
using Lumina.Presentation.Api.Common.Utilities;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Scalar.AspNetCore;
|
||||
@@ -24,6 +27,7 @@ using Serilog;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -47,6 +51,7 @@ public class Program
|
||||
builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration);
|
||||
|
||||
builder.Services.AddPresentationApiLayerServices(builder.Configuration);
|
||||
builder.Services.AddPresentationApiTelemetryServices(builder.Configuration, builder.Environment);
|
||||
builder.Services.AddApplicationLayerServices();
|
||||
builder.Services.AddInfrastructureLayerServices(builder.Configuration);
|
||||
builder.Services.AddDataAccessLayerServices();
|
||||
@@ -137,8 +142,9 @@ public class Program
|
||||
.WithDotNetFlag(true);
|
||||
});
|
||||
|
||||
// add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked
|
||||
app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub"), app => app.UseMiddleware<EventualConsistencyMiddleware>());
|
||||
// add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked,
|
||||
// and NOT for the health probes, which would otherwise begin a database transaction on every probe
|
||||
app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub") && !ctx.Request.Path.StartsWithSegments("/health"), app => app.UseMiddleware<EventualConsistencyMiddleware>());
|
||||
|
||||
// create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API
|
||||
string mediaRootDirectoryPathSetting = app.Configuration.GetValue<string>("MediaSettings:RootDirectory") ?? string.Empty;
|
||||
@@ -165,6 +171,38 @@ public class Program
|
||||
|
||||
app.MapHub<MediaLibraryScanProgressHub>("/scanProgressHub");
|
||||
|
||||
// the liveness probe reports whether the process is running, while the readiness probe also verifies that the database is reachable
|
||||
app.MapHealthChecks("/health/live", new HealthCheckOptions
|
||||
{
|
||||
Predicate = _ => false,
|
||||
ResponseWriter = WriteHealthCheckResponseAsync
|
||||
});
|
||||
app.MapHealthChecks("/health/ready", new HealthCheckOptions
|
||||
{
|
||||
Predicate = healthCheck => healthCheck.Tags.Contains("ready"),
|
||||
ResponseWriter = WriteHealthCheckResponseAsync
|
||||
});
|
||||
|
||||
await app.RunAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the health report as a JSON response.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The current HTTP context.</param>
|
||||
/// <param name="healthReport">The health report to write.</param>
|
||||
private static async Task WriteHealthCheckResponseAsync(HttpContext httpContext, HealthReport healthReport)
|
||||
{
|
||||
httpContext.Response.ContentType = "application/json";
|
||||
await httpContext.Response.WriteAsJsonAsync(new
|
||||
{
|
||||
status = healthReport.Status.ToString(),
|
||||
checks = healthReport.Entries.Select(entry => new
|
||||
{
|
||||
name = entry.Key,
|
||||
status = entry.Value.Status.ToString(),
|
||||
description = entry.Value.Description
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
"Name": "Console",
|
||||
"Args": {
|
||||
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -32,7 +32,7 @@
|
||||
"Args": {
|
||||
"path": "%LOG_PATH%lumina_api_.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}",
|
||||
"retainedFileCountLimit": 7,
|
||||
"fileSizeLimitBytes": 10485760,
|
||||
"rollOnFileSizeLimit": true,
|
||||
@@ -45,7 +45,8 @@
|
||||
"FromLogContext",
|
||||
"WithMachineName",
|
||||
"WithThreadId",
|
||||
"WithEnvironmentName"
|
||||
"WithEnvironmentName",
|
||||
"WithSpan"
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "LuminaApi"
|
||||
@@ -57,11 +58,12 @@
|
||||
"http://localhost:5012"
|
||||
]
|
||||
},
|
||||
"Kestrel": {
|
||||
"Endpoints": {
|
||||
"Http": {
|
||||
"Url": "http://localhost:5214"
|
||||
}
|
||||
}
|
||||
"Telemetry": {
|
||||
"Enabled": true,
|
||||
"ConsoleExporterEnabled": false,
|
||||
"Otlp": {
|
||||
"Endpoint": ""
|
||||
},
|
||||
"TraceSampleRatio": 0.25 // production default; override to 1.0 in the development configuration for full trace capture
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Telemetry;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using OpenTelemetry;
|
||||
using OpenTelemetry.Metrics;
|
||||
using OpenTelemetry.Resources;
|
||||
using OpenTelemetry.Trace;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Contains the OpenTelemetry services of the Presentation Web layer.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class PresentationWebTelemetryServices
|
||||
{
|
||||
private const string SERVICE_NAME = "Lumina.Web";
|
||||
|
||||
/// <summary>
|
||||
/// Registers the OpenTelemetry tracing and metrics pipelines into the dependency injection container.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add the services to.</param>
|
||||
/// <param name="configuration">Application configuration properties.</param>
|
||||
/// <param name="environment">The hosting environment of the application.</param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddPresentationWebTelemetryServices(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
|
||||
{
|
||||
bool isTelemetryEnabled = configuration.GetValue<bool?>("Telemetry:Enabled") ?? true;
|
||||
if (!isTelemetryEnabled)
|
||||
return services;
|
||||
|
||||
bool isConsoleExporterEnabled = configuration.GetValue<bool?>("Telemetry:ConsoleExporterEnabled") ?? environment.IsDevelopment();
|
||||
string? otlpEndpoint = GetOtlpEndpoint(configuration);
|
||||
double traceSampleRatio = configuration.GetValue<double?>("Telemetry:TraceSampleRatio") ?? 1.0;
|
||||
string serviceVersion = typeof(Program).Assembly.GetName().Version?.ToString() ?? "unknown";
|
||||
|
||||
services.AddOpenTelemetry()
|
||||
.ConfigureResource(resourceBuilder => resourceBuilder
|
||||
.AddService(serviceName: SERVICE_NAME, serviceVersion: serviceVersion)
|
||||
.AddEnvironmentVariableDetector()
|
||||
.AddAttributes(new Dictionary<string, object>
|
||||
{
|
||||
["deployment.environment"] = environment.EnvironmentName
|
||||
}))
|
||||
.WithTracing(tracingBuilder =>
|
||||
{
|
||||
tracingBuilder.SetSampler(CreateSampler(traceSampleRatio));
|
||||
tracingBuilder.AddSource(WebTelemetry.SOURCE_NAME);
|
||||
tracingBuilder.AddAspNetCoreInstrumentation();
|
||||
// the HTTP client instrumentation emits spans and metrics for the calls to the API, and injects the W3C trace context
|
||||
// into their headers, so that the API continues the same trace across the two separately deployed applications
|
||||
tracingBuilder.AddHttpClientInstrumentation();
|
||||
if (isConsoleExporterEnabled)
|
||||
tracingBuilder.AddConsoleExporter();
|
||||
if (otlpEndpoint is not null)
|
||||
tracingBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint));
|
||||
})
|
||||
.WithMetrics(metricsBuilder =>
|
||||
{
|
||||
metricsBuilder.AddAspNetCoreInstrumentation();
|
||||
metricsBuilder.AddHttpClientInstrumentation();
|
||||
if (isConsoleExporterEnabled)
|
||||
metricsBuilder.AddConsoleExporter();
|
||||
if (otlpEndpoint is not null)
|
||||
metricsBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpEndpoint));
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the OTLP exporter endpoint from configuration, falling back to the standard <c>OTEL_EXPORTER_OTLP_ENDPOINT</c> environment variable.
|
||||
/// </summary>
|
||||
/// <param name="configuration">Application configuration properties.</param>
|
||||
/// <returns>The OTLP endpoint, or <see langword="null"/> when no endpoint is configured.</returns>
|
||||
private static string? GetOtlpEndpoint(IConfiguration configuration)
|
||||
{
|
||||
string? endpoint = configuration.GetValue<string?>("Telemetry:Otlp:Endpoint");
|
||||
if (string.IsNullOrWhiteSpace(endpoint))
|
||||
endpoint = Environment.GetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT");
|
||||
return string.IsNullOrWhiteSpace(endpoint) ? null : endpoint;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the trace sampler used by the Web application, sampling every trace by default and honoring the configured ratio for production traffic.
|
||||
/// </summary>
|
||||
/// <param name="traceSampleRatio">The ratio of traces to sample, in the range of zero to one.</param>
|
||||
/// <returns>The configured trace sampler.</returns>
|
||||
private static Sampler CreateSampler(double traceSampleRatio)
|
||||
{
|
||||
return traceSampleRatio < 1.0
|
||||
? new ParentBasedSampler(new TraceIdRatioBasedSampler(traceSampleRatio))
|
||||
: new AlwaysOnSampler();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.HealthChecks;
|
||||
|
||||
/// <summary>
|
||||
/// Health check that verifies the remote API is reachable.
|
||||
/// </summary>
|
||||
public class ApiReachabilityHealthCheck : IHealthCheck
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly ServerConfigurationDto _serverConfiguration;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiReachabilityHealthCheck"/> class.
|
||||
/// </summary>
|
||||
/// <param name="httpClientFactory">Injected factory for creating HTTP clients.</param>
|
||||
/// <param name="serverConfigurationOptions">Injected server configuration application settings.</param>
|
||||
public ApiReachabilityHealthCheck(IHttpClientFactory httpClientFactory, IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions)
|
||||
{
|
||||
_httpClient = httpClientFactory.CreateClient();
|
||||
_serverConfiguration = serverConfigurationOptions.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the remote API is reachable by probing its readiness endpoint.
|
||||
/// </summary>
|
||||
/// <param name="context">The health check context.</param>
|
||||
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
|
||||
/// <returns>A task that represents the asynchronous operation, containing the health check result.</returns>
|
||||
public virtual async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
string healthUrl = $"{_serverConfiguration.BaseAddress}:{_serverConfiguration.Port}/health/ready";
|
||||
using CancellationTokenSource timeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeoutCancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
try
|
||||
{
|
||||
using HttpResponseMessage response = await _httpClient.GetAsync(healthUrl, timeoutCancellationTokenSource.Token).ConfigureAwait(false);
|
||||
return response.IsSuccessStatusCode
|
||||
? HealthCheckResult.Healthy()
|
||||
: HealthCheckResult.Unhealthy($"The API returned status {(int)response.StatusCode}.");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
return HealthCheckResult.Unhealthy("The API is not reachable.", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Telemetry;
|
||||
|
||||
/// <summary>
|
||||
/// Central registry of the <see cref="ActivitySource"/> used by the Presentation Web layer to emit traces.
|
||||
/// </summary>
|
||||
public static class WebTelemetry
|
||||
{
|
||||
/// <summary>
|
||||
/// The source name shared by the <see cref="ActivitySource"/> of the Presentation Web layer.
|
||||
/// </summary>
|
||||
public const string SOURCE_NAME = "Lumina.Web";
|
||||
|
||||
/// <summary>
|
||||
/// The source of the traces emitted by the Presentation Web layer.
|
||||
/// </summary>
|
||||
public static ActivitySource ActivitySource { get; } = new(SOURCE_NAME);
|
||||
}
|
||||
@@ -25,10 +25,17 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="10.9.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="10.0.11" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
|
||||
<PackageReference Include="OpenTelemetry" Version="1.18.0" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.18.0" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.18.0" />
|
||||
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.18.0" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.18.0" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.18.0" />
|
||||
<PackageReference Include="Polly" Version="8.7.0" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.16.20" />
|
||||
<PackageReference Include="Serilog" Version="4.4.0" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageReference Include="Serilog.Enrichers.Span" Version="3.1.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Web.Common.HealthChecks;
|
||||
using Lumina.Presentation.Web.Common.Utilities;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using Scalar.AspNetCore;
|
||||
@@ -35,6 +38,9 @@ public class Program
|
||||
|
||||
builder.Services.BindConfiguration(builder.Configuration);
|
||||
builder.Services.AddPresentationWebLayerServices();
|
||||
builder.Services.AddPresentationWebTelemetryServices(builder.Configuration, builder.Environment);
|
||||
builder.Services.AddHealthChecks()
|
||||
.AddCheck<ApiReachabilityHealthCheck>("api", HealthStatus.Unhealthy, ["ready"]);
|
||||
|
||||
// determine log path based on environment
|
||||
string logPath;
|
||||
@@ -122,6 +128,11 @@ public class Program
|
||||
.WithDotNetFlag(true);
|
||||
});
|
||||
|
||||
// liveness and readiness probes, probed by container orchestrators and load balancers; the readiness probe also
|
||||
// verifies that the API is reachable, so the web application is only reported ready when it can actually serve requests
|
||||
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
|
||||
app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = healthCheck => healthCheck.Tags.Contains("ready") });
|
||||
|
||||
await app.RunAsync();
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@
|
||||
"Name": "Console",
|
||||
"Args": {
|
||||
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -28,7 +28,7 @@
|
||||
"Args": {
|
||||
"path": "%LOG_PATH%lumina_web_.log",
|
||||
"rollingInterval": "Day",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
|
||||
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {TraceId} {SpanId} {Message:lj}{NewLine}{Exception}",
|
||||
"retainedFileCountLimit": 7,
|
||||
"fileSizeLimitBytes": 10485760,
|
||||
"rollOnFileSizeLimit": true,
|
||||
@@ -42,7 +42,8 @@
|
||||
"WithMachineName",
|
||||
"WithThreadId",
|
||||
"WithEnvironmentName",
|
||||
"WithRequestId"
|
||||
"WithRequestId",
|
||||
"WithSpan"
|
||||
],
|
||||
"Properties": {
|
||||
"Application": "LuminaWeb"
|
||||
@@ -54,11 +55,12 @@
|
||||
"BaseAddress": "http://localhost",
|
||||
"Port": 5214
|
||||
},
|
||||
"Kestrel": {
|
||||
"Endpoints": {
|
||||
"Http": {
|
||||
"Url": "http://localhost:5012"
|
||||
}
|
||||
}
|
||||
"Telemetry": {
|
||||
"Enabled": true,
|
||||
"ConsoleExporterEnabled": false,
|
||||
"Otlp": {
|
||||
"Endpoint": ""
|
||||
},
|
||||
"TraceSampleRatio": 0.25 // production default; override to 1.0 in the development configuration for full trace capture
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user