fix(telemetry): redact after ConfigureLogger enrichers, keep colliding dictionary keys, require http(s) OTLP endpoint and validate the options overload; bump 0.2.1 (scadaproj#48)

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 14:57:48 -05:00
parent 5bf2f2caf1
commit 1786bab0a0
12 changed files with 182 additions and 25 deletions
@@ -136,6 +136,19 @@ public sealed class RedactionEnricher : ILogEventEnricher
foreach (var pair in dictionary.Elements)
{
var key = pair.Key.Value?.ToString() ?? NullKey;
// Distinct keys can print identically (DateTime keys differing below one second,
// a null key next to ""). Keep every entry: later collisions get a "#n" suffix in
// the redactor's view, and OriginalKeys restores the real key on rebuild.
if (projectedDictionary.ContainsKey(key))
{
var baseKey = key;
for (var n = 2; projectedDictionary.ContainsKey(key); n++)
{
key = baseKey + "#" + n;
}
}
projectedDictionary[key] = Project(pair.Value);
projectedDictionary.OriginalKeys[key] = pair.Key;
}
@@ -72,7 +72,7 @@ internal static class ZbSerilogConfig
if (serviceProvider is not null)
{
enrich.With(new RedactionEnricher(serviceProvider));
ApplyRedaction(loggerConfiguration, serviceProvider);
}
ApplyOpenTelemetryExport(loggerConfiguration, options);
@@ -80,6 +80,16 @@ internal static class ZbSerilogConfig
return loggerConfiguration;
}
/// <summary>
/// Registers the <see cref="RedactionEnricher"/>. Must be the LAST enricher registered so that
/// every other enricher (including ones a host adds through <c>ZbSerilogOptions.ConfigureLogger</c>)
/// has stamped its properties before redaction runs.
/// </summary>
/// <param name="loggerConfiguration">The Serilog configuration.</param>
/// <param name="serviceProvider">Provider used to lazily resolve <c>ILogRedactor</c>.</param>
internal static void ApplyRedaction(LoggerConfiguration loggerConfiguration, IServiceProvider serviceProvider) =>
loggerConfiguration.Enrich.With(new RedactionEnricher(serviceProvider));
/// <summary>
/// Adds a <c>WriteTo.OpenTelemetry</c> log sink when an OTLP exporter is explicitly
/// selected (<see cref="ZbTelemetryOptions.Exporter"/> = <see cref="ZbExporter.Otlp"/>).
@@ -115,9 +115,15 @@ public static class ZbSerilogExtensions
loggerConfiguration.MinimumLevel.Is(governed);
}
ZbSerilogConfig.Apply(loggerConfiguration, options, serviceProvider);
// Redaction is deliberately applied AFTER the hook (Telemetry-009): Serilog runs
// enrichers in registration order, so a RedactionEnricher registered before
// ConfigureLogger would let hook-added enrichers stamp properties that reach every
// sink unredacted. Apply() is told there is no provider so it skips redaction here.
ZbSerilogConfig.Apply(loggerConfiguration, options, serviceProvider: null);
serilogOptions.ConfigureLogger?.Invoke(loggerConfiguration, serviceProvider);
ZbSerilogConfig.ApplyRedaction(loggerConfiguration, serviceProvider);
},
preserveStaticLogger: true);
@@ -41,7 +41,8 @@ public sealed class ZbSerilogOptions
/// <summary>
/// Final, app-specific adjustments to the <see cref="LoggerConfiguration"/> — filters,
/// extra enrichers, extra sinks — run after the governed level and the shared
/// enricher/redaction/export set. Receives the application <see cref="IServiceProvider"/>.
/// enricher/export set. Redaction is registered after this hook, so properties stamped by enrichers
/// added here ARE passed through <c>ILogRedactor</c>. Receives the application <see cref="IServiceProvider"/>.
/// </summary>
public Action<LoggerConfiguration, IServiceProvider>? ConfigureLogger { get; set; }
}
@@ -44,6 +44,10 @@ public static class ZbTelemetryExtensions
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(options);
// The lambda overloads validate in BuildOptions; a caller-built options object must get the
// same fail-fast treatment (Telemetry-011).
ValidateRequired(options, nameof(options));
services.AddOpenTelemetry()
.ConfigureResource(rb => ZbResource.Configure(rb, options))
.WithMetrics(metrics =>
@@ -95,14 +99,19 @@ public static class ZbTelemetryExtensions
ArgumentNullException.ThrowIfNull(configure);
var options = new ZbTelemetryOptions();
configure(options);
ValidateRequired(options, nameof(configure));
return options;
}
private static void ValidateRequired(ZbTelemetryOptions options, string paramName)
{
if (string.IsNullOrWhiteSpace(options.ServiceName))
{
throw new ArgumentException(
"ZbTelemetryOptions.ServiceName is required (e.g. \"otopcua\").",
nameof(configure));
paramName);
}
ZbTelemetryOptionsValidator.Validate(options, nameof(configure));
return options;
ZbTelemetryOptionsValidator.Validate(options, paramName);
}
private static void ApplyMetricsExporter(MeterProviderBuilder metrics, ZbTelemetryOptions options)
@@ -11,7 +11,7 @@ internal static class ZbTelemetryOptionsValidator
/// <summary>
/// Validates the OTLP configuration. When <see cref="ZbTelemetryOptions.Exporter"/> is
/// <see cref="ZbExporter.Otlp"/>, <see cref="ZbTelemetryOptions.OtlpEndpoint"/> must be a
/// non-empty, well-formed absolute URI. Throws an <see cref="ArgumentException"/> (naming the
/// non-empty, well-formed absolute <c>http</c>/<c>https</c> URI with a host. Throws an <see cref="ArgumentException"/> (naming the
/// option) otherwise. No-op for the Prometheus exporter — a stray endpoint is ignored there.
/// </summary>
/// <param name="options">The populated telemetry options to validate.</param>
@@ -33,10 +33,15 @@ internal static class ZbTelemetryOptionsValidator
paramName);
}
if (!Uri.TryCreate(options.OtlpEndpoint, UriKind.Absolute, out _))
// A scheme-less "host:port" (e.g. "collector:4317") parses as an absolute URI whose scheme
// is the host name, so TryCreate alone accepts the exact typo this check exists to catch
// (Telemetry-011). OTLP exporters speak http/https only.
if (!Uri.TryCreate(options.OtlpEndpoint, UriKind.Absolute, out var uri)
|| (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
|| string.IsNullOrEmpty(uri.Host))
{
throw new ArgumentException(
$"ZbTelemetryOptions.OtlpEndpoint is not a well-formed absolute URI: " +
$"ZbTelemetryOptions.OtlpEndpoint is not a well-formed absolute http(s) URI: " +
$"'{options.OtlpEndpoint}' (expected e.g. \"http://collector:4317\").",
paramName);
}