feat(telemetry.serilog): AddZbSerilog bootstrap + identity enrichers

This commit is contained in:
Joseph Doherty
2026-06-01 07:38:07 -04:00
parent 3e4d4369bf
commit 1344f249d0
4 changed files with 211 additions and 0 deletions
@@ -0,0 +1,27 @@
namespace ZB.MOM.WW.Telemetry.Serilog;
/// <summary>
/// Canonical Serilog property name constants for the identity enrichers stamped by
/// <see cref="ZbSerilogExtensions.AddZbSerilog"/>. Use these constants — not literal strings —
/// when querying properties in sinks or tests. Each property mirrors a shared OTel Resource
/// attribute so logs and metrics/traces from the same node carry identical dimensions.
/// </summary>
public static class ZbLogEnricherNames
{
/// <summary>
/// Serilog property: physical or logical site identifier. Matches OTel Resource <c>site.id</c>.
/// </summary>
public const string SiteId = "SiteId";
/// <summary>
/// Serilog property: node function (<c>central</c>, <c>site</c>, <c>hub</c>, <c>standalone</c>).
/// Matches OTel Resource <c>node.role</c>.
/// </summary>
public const string NodeRole = "NodeRole";
/// <summary>
/// Serilog property: machine name (<see cref="System.Environment.MachineName"/>).
/// Matches OTel Resource <c>host.name</c>. Populated automatically — not a caller-supplied option.
/// </summary>
public const string NodeHostname = "NodeHostname";
}
@@ -0,0 +1,69 @@
using System;
using Serilog;
using Serilog.Configuration;
using ZB.MOM.WW.Telemetry;
namespace ZB.MOM.WW.Telemetry.Serilog;
/// <summary>
/// Reusable seam that applies the shared ZB.MOM.WW logging configuration (identity enrichers,
/// trace-context correlation, redaction, and OTel log export) to a
/// <see cref="LoggerConfiguration"/>. Shared by <see cref="ZbSerilogExtensions.AddZbSerilog"/>
/// and unit tests so both exercise an identical enricher/sink set.
/// </summary>
public static class ZbSerilogConfig
{
/// <summary>
/// Applies the shared identity enrichers — <see cref="ZbLogEnricherNames.SiteId"/> and
/// <see cref="ZbLogEnricherNames.NodeRole"/> from <paramref name="options"/>, and
/// <see cref="ZbLogEnricherNames.NodeHostname"/> from
/// <see cref="System.Environment.MachineName"/> (auto, never a caller-supplied option) — to
/// <paramref name="loggerConfiguration"/>. <c>SiteId</c>/<c>NodeRole</c> are stamped only when
/// the option is non-null/non-empty, mirroring the shared OTel Resource omission rules.
/// </summary>
/// <param name="loggerConfiguration">The Serilog configuration to enrich.</param>
/// <param name="options">The telemetry options describing the service identity.</param>
/// <returns>The same <paramref name="loggerConfiguration"/> for chaining.</returns>
public static LoggerConfiguration Apply(
LoggerConfiguration loggerConfiguration,
ZbTelemetryOptions options) =>
Apply(loggerConfiguration, options, serviceProvider: null);
/// <summary>
/// Overload of <see cref="Apply(LoggerConfiguration, ZbTelemetryOptions)"/> that additionally
/// wires the service-provider-dependent stages — the redaction enricher (which lazily resolves
/// a registered <c>ILogRedactor</c>). When <paramref name="serviceProvider"/> is null, only the
/// provider-independent enrichers are applied.
/// </summary>
/// <param name="loggerConfiguration">The Serilog configuration to enrich.</param>
/// <param name="options">The telemetry options describing the service identity.</param>
/// <param name="serviceProvider">
/// Provider used to lazily resolve project-supplied seams (e.g. <c>ILogRedactor</c>);
/// may be null in tests or pipelines without DI.
/// </param>
/// <returns>The same <paramref name="loggerConfiguration"/> for chaining.</returns>
public static LoggerConfiguration Apply(
LoggerConfiguration loggerConfiguration,
ZbTelemetryOptions options,
IServiceProvider? serviceProvider)
{
ArgumentNullException.ThrowIfNull(loggerConfiguration);
ArgumentNullException.ThrowIfNull(options);
LoggerEnrichmentConfiguration enrich = loggerConfiguration.Enrich;
if (!string.IsNullOrEmpty(options.SiteId))
{
enrich.WithProperty(ZbLogEnricherNames.SiteId, options.SiteId);
}
if (!string.IsNullOrEmpty(options.NodeRole))
{
enrich.WithProperty(ZbLogEnricherNames.NodeRole, options.NodeRole);
}
enrich.WithProperty(ZbLogEnricherNames.NodeHostname, Environment.MachineName);
return loggerConfiguration;
}
}
@@ -0,0 +1,69 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using ZB.MOM.WW.Telemetry;
namespace ZB.MOM.WW.Telemetry.Serilog;
/// <summary>
/// Extension point for configuring the shared Serilog bootstrap on an
/// <see cref="IHostApplicationBuilder"/>. Wires config-driven sinks
/// (<c>ReadFrom.Configuration</c>), an explicit minimum level (<c>Serilog:MinimumLevel</c>,
/// default <see cref="LogEventLevel.Information"/>), and the shared enricher/redaction/OTel-export
/// set via <see cref="ZbSerilogConfig"/>. Does NOT configure OTel metrics/traces — call
/// <c>AddZbTelemetry</c> in the core package for that.
/// </summary>
public static class ZbSerilogExtensions
{
/// <summary>
/// Registers Serilog on the host with the shared ZB.MOM.WW configuration: sinks read from
/// <see cref="IConfiguration"/> (<c>ReadFrom.Configuration</c>), an explicit minimum level
/// (<c>Serilog:MinimumLevel</c>, default <see cref="LogEventLevel.Information"/>), and the
/// identity enrichers (<c>SiteId</c>/<c>NodeRole</c> from <paramref name="configure"/>,
/// <c>NodeHostname</c> = <see cref="System.Environment.MachineName"/>). The
/// <paramref name="configure"/> delegate receives the same <see cref="ZbTelemetryOptions"/>
/// used by <c>AddZbTelemetry</c> — typically share one options-population lambda across both.
/// </summary>
/// <param name="builder">The host application builder.</param>
/// <param name="configure">Populates the <see cref="ZbTelemetryOptions"/>.</param>
public static IHostApplicationBuilder AddZbSerilog(
this IHostApplicationBuilder builder,
Action<ZbTelemetryOptions> configure)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(configure);
var options = new ZbTelemetryOptions();
configure(options);
var minimumLevel = ReadMinimumLevel(builder.Configuration);
builder.Services.AddSerilog((serviceProvider, loggerConfiguration) =>
{
loggerConfiguration
.ReadFrom.Configuration(builder.Configuration)
.MinimumLevel.Is(minimumLevel);
ZbSerilogConfig.Apply(loggerConfiguration, options, serviceProvider);
});
return builder;
}
/// <summary>
/// Reads <c>Serilog:MinimumLevel</c> (or the nested <c>Serilog:MinimumLevel:Default</c>) from
/// configuration, falling back to <see cref="LogEventLevel.Information"/> for missing or
/// unparseable values.
/// </summary>
private static LogEventLevel ReadMinimumLevel(IConfiguration configuration)
{
var raw = configuration["Serilog:MinimumLevel"]
?? configuration["Serilog:MinimumLevel:Default"];
return Enum.TryParse<LogEventLevel>(raw, ignoreCase: true, out var parsed)
? parsed
: LogEventLevel.Information;
}
}
@@ -0,0 +1,46 @@
using Serilog;
using Serilog.Events;
using Serilog.Sinks.InMemory;
using ZB.MOM.WW.Telemetry;
using ZB.MOM.WW.Telemetry.Serilog;
namespace ZB.MOM.WW.Telemetry.Serilog.Tests;
public sealed class EnricherTests
{
private static string ScalarValue(LogEvent logEvent, string propertyName)
{
Assert.True(
logEvent.Properties.TryGetValue(propertyName, out var value),
$"expected property '{propertyName}' to be present");
var scalar = Assert.IsType<ScalarValue>(value);
return scalar.Value?.ToString() ?? "";
}
[Fact]
public void Identity_enrichers_stamp_SiteId_NodeRole_and_NodeHostname()
{
var sink = new InMemorySink();
var options = new ZbTelemetryOptions
{
ServiceName = "otopcua",
SiteId = "s1",
NodeRole = "Central",
};
var loggerConfig = new LoggerConfiguration();
ZbSerilogConfig.Apply(loggerConfig, options);
using var logger = loggerConfig
.WriteTo.Sink(sink)
.CreateLogger();
logger.Information("hello");
var logEvent = Assert.Single(sink.LogEvents);
Assert.Equal("s1", ScalarValue(logEvent, ZbLogEnricherNames.SiteId));
Assert.Equal("Central", ScalarValue(logEvent, ZbLogEnricherNames.NodeRole));
Assert.Equal(
Environment.MachineName,
ScalarValue(logEvent, ZbLogEnricherNames.NodeHostname));
}
}