Adds telemetry instrumentation to application handlers

This commit is contained in:
BinaryAlley committed 2026-08-22 06:27:31 -07:00
1 parent ffcb25c13f
commit a2c99b1b79
13 files changed
+862 -2

No files matched your search

@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Telemetry;
using Lumina.Domain.Common.Events;
using Microsoft.Extensions.DependencyInjection;
using System;
@@ -46,9 +47,18 @@ public static class ApplicationLayerServices
continue;
if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
{
services.AddSingleton(registration.Contract, registration.Implementation);
else
services.AddScoped(registration.Contract, registration.Implementation);
continue;
}
// wrap query, command, and domain event handlers in their telemetry decorator, so that every invocation emits traces, metrics, and structured logs
services.AddScoped(registration.Contract, serviceProvider =>
{
object handler = ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, registration.Implementation);
Type decoratorType = TelemetryDecoratorFactory.GetDecoratorType(registration.Contract);
return ActivatorUtilities.CreateInstance(serviceProvider, decoratorType, handler);
});
}
return services;
@@ -0,0 +1,108 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Diagnostics.Metrics;
#endregion
namespace Lumina.Application.Common.Telemetry;
/// <summary>
/// Helper that emits the traces, metrics, and structured logs for the execution of application handlers.
/// </summary>
internal static class ApplicationHandlerTelemetry
{
private const string HANDLER_DURATION_METRIC_NAME = "lumina.application.handler.duration";
private const string HANDLER_INVOCATIONS_METRIC_NAME = "lumina.application.handler.invocations";
private static readonly Histogram<double> s_handlerDuration = ApplicationTelemetry.Meter.CreateHistogram<double>(
name: HANDLER_DURATION_METRIC_NAME,
description: "Duration in milliseconds of the execution of an application handler.");
private static readonly Counter<long> s_handlerInvocations = ApplicationTelemetry.Meter.CreateCounter<long>(
name: HANDLER_INVOCATIONS_METRIC_NAME,
description: "Number of invocations of an application handler.");
/// <summary>
/// Starts a new <see cref="Activity"/> for the execution of the handler with the specified name.
/// </summary>
/// <param name="handlerName">The name of the handler being executed.</param>
/// <param name="handlerType">The type of the handler being executed.</param>
/// <returns>The started activity, or <see langword="null"/> when no trace listener is registered.</returns>
public static Activity? StartActivity(string handlerName, string handlerType)
{
Activity? activity = ApplicationTelemetry.ActivitySource.StartActivity($"Handle {handlerName}", ActivityKind.Internal);
activity?.SetTag("lumina.handler.type", handlerType);
activity?.SetTag("lumina.handler.name", handlerName);
return activity;
}
/// <summary>
/// Records the successful completion of a handler execution, including its trace status, metrics, and a structured log entry.
/// </summary>
/// <param name="logger">The logger to write the structured log entry to.</param>
/// <param name="activity">The activity to mark as successful.</param>
/// <param name="handlerName">The name of the handled handler.</param>
/// <param name="handlerType">The type of the handled handler.</param>
/// <param name="duration">The duration of the handler execution.</param>
public static void RecordSuccess(ILogger logger, Activity? activity, string handlerName, string handlerType, TimeSpan duration)
{
activity?.SetStatus(ActivityStatusCode.Ok);
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: true);
logger.LogDebug("Completed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds);
}
/// <summary>
/// Records the failed completion of a handler execution, including its trace status, metrics, and a structured log entry.
/// </summary>
/// <param name="logger">The logger to write the structured log entry to.</param>
/// <param name="activity">The activity to mark as failed.</param>
/// <param name="handlerName">The name of the handled handler.</param>
/// <param name="handlerType">The type of the handled handler.</param>
/// <param name="duration">The duration of the handler execution.</param>
/// <param name="error">An optional description of the failure.</param>
public static void RecordFailure(ILogger logger, Activity? activity, string handlerName, string handlerType, TimeSpan duration, string? error)
{
activity?.SetStatus(ActivityStatusCode.Error, error);
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false);
// business-rule failures are routine outcomes (e.g. failed logins), so log at Debug to avoid noise from high-frequency handlers
logger.LogDebug("Failed handling {HandlerType} {HandlerName} in {DurationMs}ms: {Error}", handlerType, handlerName, duration.TotalMilliseconds, error);
}
/// <summary>
/// Records the exceptional completion of a handler execution, including its trace status, metrics, and a structured log entry.
/// </summary>
/// <param name="logger">The logger to write the structured log entry to.</param>
/// <param name="activity">The activity to mark as failed.</param>
/// <param name="handlerName">The name of the handled handler.</param>
/// <param name="handlerType">The type of the handled handler.</param>
/// <param name="exception">The exception that was thrown during the handler execution.</param>
/// <param name="duration">The duration of the handler execution.</param>
public static void RecordException(ILogger logger, Activity? activity, string handlerName, string handlerType, Exception exception, TimeSpan duration)
{
activity?.SetStatus(ActivityStatusCode.Error, exception.Message);
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false);
logger.LogError(exception, "Failed handling {HandlerType} {HandlerName} in {DurationMs}ms", handlerType, handlerName, duration.TotalMilliseconds);
}
/// <summary>
/// Records the invocation count and duration of a handler execution into the corresponding metrics, and tags the activity with the outcome.
/// </summary>
/// <param name="activity">The activity to tag with the outcome.</param>
/// <param name="handlerName">The name of the handled handler.</param>
/// <param name="handlerType">The type of the handled handler.</param>
/// <param name="duration">The duration of the handler execution.</param>
/// <param name="isSuccess">Whether the handler execution completed successfully.</param>
private static void RecordOutcome(Activity? activity, string handlerName, string handlerType, TimeSpan duration, bool isSuccess)
{
TagList tags = new()
{
{ "lumina.handler.type", handlerType },
{ "lumina.handler.name", handlerName },
{ "lumina.outcome", isSuccess ? "success" : "failure" }
};
s_handlerInvocations.Add(1, tags);
s_handlerDuration.Record(duration.TotalMilliseconds, tags);
activity?.SetTag("lumina.outcome", isSuccess ? "success" : "failure");
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using System.Diagnostics.Metrics;
#endregion
namespace Lumina.Application.Common.Telemetry;
/// <summary>
/// Central registry of the <see cref="ActivitySource"/> and <see cref="Meter"/> used by the Application layer to emit traces and metrics.
/// </summary>
public static class ApplicationTelemetry
{
/// <summary>
/// The source name shared by the <see cref="ActivitySource"/> and <see cref="Meter"/> of the Application layer.
/// </summary>
public const string SOURCE_NAME = "Lumina.Application";
/// <summary>
/// The source of the traces emitted by the Application layer.
/// </summary>
public static ActivitySource ActivitySource { get; } = new(SOURCE_NAME);
/// <summary>
/// The source of the metrics emitted by the Application layer.
/// </summary>
public static Meter Meter { get; } = new(SOURCE_NAME);
}
@@ -0,0 +1,63 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Concurrent;
using System.Reflection;
#endregion
namespace Lumina.Application.Common.Telemetry;
/// <summary>
/// Detects the outcome of an application handler result in a generic way, without coupling the telemetry decorators to any concrete result type.
/// </summary>
internal static class HandlerOutcomeDetector
{
private static readonly ConcurrentDictionary<Type, PropertyInfo?> s_isSuccessPropertyCache = new();
private static readonly ConcurrentDictionary<Type, PropertyInfo?> s_firstErrorPropertyCache = new();
private static readonly ConcurrentDictionary<Type, PropertyInfo?> s_errorDescriptionPropertyCache = new();
/// <summary>
/// Determines whether the specified result represents a successful outcome.
/// </summary>
/// <param name="result">The result returned by an application handler, or <see langword="null"/>.</param>
/// <returns>
/// <see langword="true"/> when the result reports success, when it is <see langword="null"/>, or when it exposes no success flag.
/// </returns>
/// <remarks>
/// Handlers that return plain DTOs (no <c>IsSuccess</c> property) cannot express a failure and are reported as successful;
/// only handlers returning a result type such as <see cref="Domain.Common.Primitives.Result{TValue}"/> report failures.
/// </remarks>
public static bool IsSuccessful(object? result)
{
if (result is null)
return true;
PropertyInfo? isSuccessProperty = GetIsSuccessProperty(result.GetType());
return isSuccessProperty is null || (bool)isSuccessProperty.GetValue(result)!;
}
/// <summary>
/// Gets a human-readable description of the first error of a failed result, when the result exposes one.
/// </summary>
/// <param name="result">The failed result returned by an application handler, or <see langword="null"/>.</param>
/// <returns>The description of the first error, or <see langword="null"/> when the result exposes no errors.</returns>
public static string? GetErrorDescription(object? result)
{
if (result is null)
return null;
PropertyInfo? firstErrorProperty = s_firstErrorPropertyCache.GetOrAdd(result.GetType(), type => type.GetProperty("FirstError", BindingFlags.Public | BindingFlags.Instance));
object? firstError = firstErrorProperty?.GetValue(result);
if (firstError is null)
return null;
PropertyInfo? descriptionProperty = s_errorDescriptionPropertyCache.GetOrAdd(firstError.GetType(), type => type.GetProperty("Description", BindingFlags.Public | BindingFlags.Instance));
return descriptionProperty?.GetValue(firstError)?.ToString();
}
/// <summary>
/// Gets the public instance <c>IsSuccess</c> property of the specified type, if it has one.
/// </summary>
/// <param name="type">The type to inspect.</param>
/// <returns>The <c>IsSuccess</c> property, or <see langword="null"/> when the type does not expose one.</returns>
private static PropertyInfo? GetIsSuccessProperty(Type type)
{
return s_isSuccessPropertyCache.GetOrAdd(type, candidateType => candidateType.GetProperty("IsSuccess", BindingFlags.Public | BindingFlags.Instance));
}
}
@@ -0,0 +1,65 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.Telemetry;
/// <summary>
/// Decorator that wraps an <see cref="ICommandHandler{TCommand,TResult}"/> to emit traces, metrics, and structured logs for every command execution.
/// </summary>
/// <typeparam name="TCommand">The type of command to handle.</typeparam>
/// <typeparam name="TResult">The type of result returned after handling the command.</typeparam>
public class TelemetryCommandHandlerDecorator<TCommand, TResult> : ICommandHandler<TCommand, TResult> where TCommand : ICommand
{
private const string HANDLER_TYPE = "command";
private readonly ICommandHandler<TCommand, TResult> _innerHandler;
private readonly ILogger<TelemetryCommandHandlerDecorator<TCommand, TResult>> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryCommandHandlerDecorator{TCommand,TResult}"/> class.
/// </summary>
/// <param name="innerHandler">The wrapped command handler.</param>
/// <param name="logger">Injected logger used for structured logging.</param>
public TelemetryCommandHandlerDecorator(ICommandHandler<TCommand, TResult> innerHandler, ILogger<TelemetryCommandHandlerDecorator<TCommand, TResult>> logger)
{
_innerHandler = innerHandler;
_logger = logger;
}
/// <summary>
/// Handles the specified command, emitting telemetry around the execution of the wrapped handler.
/// </summary>
/// <param name="command">The command to handle.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation, containing the result of the command execution.</returns>
public async Task<TResult> HandleAsync(TCommand command, CancellationToken cancellationToken)
{
string handlerName = _innerHandler.GetType().Name;
using (Activity? activity = ApplicationHandlerTelemetry.StartActivity(handlerName, HANDLER_TYPE))
{
Stopwatch stopwatch = Stopwatch.StartNew();
try
{
TResult result = await _innerHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
stopwatch.Stop();
if (HandlerOutcomeDetector.IsSuccessful(result))
ApplicationHandlerTelemetry.RecordSuccess(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed);
else
ApplicationHandlerTelemetry.RecordFailure(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed, HandlerOutcomeDetector.GetErrorDescription(result));
return result;
}
catch (Exception exception)
{
stopwatch.Stop();
ApplicationHandlerTelemetry.RecordException(_logger, activity, handlerName, HANDLER_TYPE, exception, stopwatch.Elapsed);
throw;
}
}
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Domain.Common.Events;
using System;
#endregion
namespace Lumina.Application.Common.Telemetry;
/// <summary>
/// Resolves the telemetry decorator type that wraps a given application handler contract.
/// </summary>
internal static class TelemetryDecoratorFactory
{
/// <summary>
/// Gets the closed telemetry decorator type for the specified handler contract.
/// </summary>
/// <param name="contract">The handler contract to wrap.</param>
/// <returns>The closed generic telemetry decorator type for the contract.</returns>
/// <exception cref="ArgumentException">Thrown when the contract has no matching telemetry decorator.</exception>
public static Type GetDecoratorType(Type contract)
{
Type contractDefinition = contract.GetGenericTypeDefinition();
Type[] typeArguments = contract.GetGenericArguments();
if (contractDefinition == typeof(IQueryHandler<,>))
return typeof(TelemetryQueryHandlerDecorator<,>).MakeGenericType(typeArguments);
if (contractDefinition == typeof(ICommandHandler<,>))
return typeof(TelemetryCommandHandlerDecorator<,>).MakeGenericType(typeArguments);
if (contractDefinition == typeof(IDomainEventHandler<>))
return typeof(TelemetryDomainEventHandlerDecorator<>).MakeGenericType(typeArguments);
throw new ArgumentException($"No telemetry decorator is defined for the contract type '{contract}'.", nameof(contract));
}
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.Telemetry;
/// <summary>
/// Decorator that wraps an <see cref="IDomainEventHandler{TDomainEvent}"/> to emit traces, metrics, and structured logs for every domain event handling.
/// </summary>
/// <typeparam name="TDomainEvent">The type of domain event to handle.</typeparam>
public class TelemetryDomainEventHandlerDecorator<TDomainEvent> : IDomainEventHandler<TDomainEvent> where TDomainEvent : IDomainEvent
{
private const string HANDLER_TYPE = "domain-event";
private readonly IDomainEventHandler<TDomainEvent> _innerHandler;
private readonly ILogger<TelemetryDomainEventHandlerDecorator<TDomainEvent>> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryDomainEventHandlerDecorator{TDomainEvent}"/> class.
/// </summary>
/// <param name="innerHandler">The wrapped domain event handler.</param>
/// <param name="logger">Injected logger used for structured logging.</param>
public TelemetryDomainEventHandlerDecorator(IDomainEventHandler<TDomainEvent> innerHandler, ILogger<TelemetryDomainEventHandlerDecorator<TDomainEvent>> logger)
{
_innerHandler = innerHandler;
_logger = logger;
}
/// <summary>
/// Handles the specified domain event, emitting telemetry around the execution of the wrapped handler.
/// </summary>
/// <param name="domainEvent">The domain event to handle.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public async ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken)
{
string handlerName = _innerHandler.GetType().Name;
using (Activity? activity = ApplicationHandlerTelemetry.StartActivity(handlerName, HANDLER_TYPE))
{
Stopwatch stopwatch = Stopwatch.StartNew();
try
{
await _innerHandler.HandleAsync(domainEvent, cancellationToken).ConfigureAwait(false);
stopwatch.Stop();
ApplicationHandlerTelemetry.RecordSuccess(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed);
}
catch (Exception exception)
{
stopwatch.Stop();
ApplicationHandlerTelemetry.RecordException(_logger, activity, handlerName, HANDLER_TYPE, exception, stopwatch.Elapsed);
throw;
}
}
}
}
@@ -0,0 +1,65 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.Telemetry;
/// <summary>
/// Decorator that wraps an <see cref="IQueryHandler{TQuery,TResult}"/> to emit traces, metrics, and structured logs for every query execution.
/// </summary>
/// <typeparam name="TQuery">The type of query to handle.</typeparam>
/// <typeparam name="TResult">The type of result returned after handling the query.</typeparam>
public class TelemetryQueryHandlerDecorator<TQuery, TResult> : IQueryHandler<TQuery, TResult> where TQuery : IQuery
{
private const string HANDLER_TYPE = "query";
private readonly IQueryHandler<TQuery, TResult> _innerHandler;
private readonly ILogger<TelemetryQueryHandlerDecorator<TQuery, TResult>> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TelemetryQueryHandlerDecorator{TQuery,TResult}"/> class.
/// </summary>
/// <param name="innerHandler">The wrapped query handler.</param>
/// <param name="logger">Injected logger used for structured logging.</param>
public TelemetryQueryHandlerDecorator(IQueryHandler<TQuery, TResult> innerHandler, ILogger<TelemetryQueryHandlerDecorator<TQuery, TResult>> logger)
{
_innerHandler = innerHandler;
_logger = logger;
}
/// <summary>
/// Handles the specified query, emitting telemetry around the execution of the wrapped handler.
/// </summary>
/// <param name="query">The query to handle.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation, containing the result of the query execution.</returns>
public async Task<TResult> HandleAsync(TQuery query, CancellationToken cancellationToken)
{
string handlerName = _innerHandler.GetType().Name;
using (Activity? activity = ApplicationHandlerTelemetry.StartActivity(handlerName, HANDLER_TYPE))
{
Stopwatch stopwatch = Stopwatch.StartNew();
try
{
TResult result = await _innerHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false);
stopwatch.Stop();
if (HandlerOutcomeDetector.IsSuccessful(result))
ApplicationHandlerTelemetry.RecordSuccess(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed);
else
ApplicationHandlerTelemetry.RecordFailure(_logger, activity, handlerName, HANDLER_TYPE, stopwatch.Elapsed, HandlerOutcomeDetector.GetErrorDescription(result));
return result;
}
catch (Exception exception)
{
stopwatch.Stop();
ApplicationHandlerTelemetry.RecordException(_logger, activity, handlerName, HANDLER_TYPE, exception, stopwatch.Elapsed);
throw;
}
}
}
}