#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Telemetry; using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Metrics; #endregion namespace Lumina.Application.UnitTests.Common.Telemetry; /// /// Test utilities for capturing the traces and metrics emitted by the application telemetry. /// [ExcludeFromCodeCoverage] internal static class TelemetryTestHelpers { /// /// Creates an that captures every activity emitted by the activity source. /// /// The collection that stopped activities are added to. /// The started . public static ActivityListener CreateActivityListener(ICollection capturedActivities) { ActivityListener listener = new() { ShouldListenTo = source => source.Name == ApplicationTelemetry.SOURCE_NAME, Sample = (ref ActivityCreationOptions options) => ActivitySamplingResult.AllData, ActivityStopped = activity => capturedActivities.Add(activity) }; ActivitySource.AddActivityListener(listener); return listener; } /// /// Creates a that captures every measurement emitted by the meter. /// /// The collection that measurements are added to. /// The started . public static MeterListener CreateMeterListener(ICollection<(string InstrumentName, double Value, string Outcome)> measurements) { MeterListener listener = new() { InstrumentPublished = (instrument, meterListener) => { if (instrument.Meter.Name == ApplicationTelemetry.SOURCE_NAME) meterListener.EnableMeasurementEvents(instrument); } }; // InstrumentPublished fires for instruments created after Start(), and Start() also replays every instrument // that already exists on the meter; therefore the lazily-initialized static handler instruments are captured by // every listener, whether they were created before or during the test. listener.SetMeasurementEventCallback((instrument, value, tags, state) => measurements.Add((instrument.Name, value, GetOutcomeTag(tags)))); listener.SetMeasurementEventCallback((instrument, value, tags, state) => measurements.Add((instrument.Name, value, GetOutcomeTag(tags)))); listener.Start(); return listener; } /// /// Reads the value of the lumina.outcome tag from the specified tag list. /// /// The tag list of a measurement. /// The outcome tag value, or an empty string when the tag is not present. private static string GetOutcomeTag(ReadOnlySpan> tags) { foreach (KeyValuePair tag in tags) if (tag.Key == "lumina.outcome") return tag.Value?.ToString() ?? string.Empty; return string.Empty; } }