feat(host): build the process logger through the shared AddZbSerilog bootstrap (#94)
Switch ScadaBridge from its own LoggerConfigurationFactory to AddZbSerilog (ZB.MOM.WW.Telemetry(.Serilog) 0.1.0 -> 0.2.0) using the two 0.2.0 hooks: - MinimumLevelGovernor: ScadaBridge:Logging:MinimumLevel, applied after ReadFrom.Configuration so it outranks Serilog:MinimumLevel (never null, so the floor never defers to the Serilog key; Override:* namespace entries still apply; the one-shot conflict / unparseable-value warnings are unchanged). - ConfigureLogger: the standby active-node exclusion filter (register row 71), the configured node identity (the shared bootstrap stamps NodeHostname from the machine name and skips empty values; an overwriting enricher keeps the configured ScadaBridge:Node values verbatim), Enrich.FromLogContext and the ExecutionLogCaptureSink. ScadaBridgeLogging runs AddZbSerilog on a small pre-host builder and Program installs the result as the static Log.Logger; both web hosts keep UseSerilog() over it. One logger and one file-sink handle per process, usable before the host is built (startup banner, warnings, pre-host Fatal), by SerilogAkkaLogger, and after the host is disposed (shutdown line, unexpected-termination Fatal) — AddZbSerilog's own DI registration would leave Log.Logger alone and have the host dispose the logger. LoggerConfigurationFactory is deleted (nothing else used it). Tests: existing logging/standby/sink tests now run through the new pipeline, plus ScadaBridgeLoggingParityTests (level precedence, Override:* still applies, one-shot warning, configured identity incl. NodeHostname != MachineName and empty SiteId, exact property set of a plain line, trace_id/span_id). Mutation-checked: governor deferring, filter removed, identity enricher removed, FromLogContext removed, capture sink removed each fail tests. Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
@@ -23,10 +23,8 @@ public class LoggerConfigurationTests
|
||||
public void MinimumLevel_Warning_SuppressesInformationLogs()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
var logger = LoggerConfigurationFactory
|
||||
.Build(BuildConfig("Warning"), "Central", "central", "node1")
|
||||
.WriteTo.Sink(sink)
|
||||
.CreateLogger();
|
||||
var logger = ScadaBridgeLogging.CreateLogger(
|
||||
BuildConfig("Warning"), "Central", "central", "node1", new StringWriter(), lc => lc.WriteTo.Sink(sink));
|
||||
|
||||
logger.Information("info message");
|
||||
logger.Warning("warning message");
|
||||
@@ -40,10 +38,8 @@ public class LoggerConfigurationTests
|
||||
public void LogContextProperties_AreEnrichedOntoEvents()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
var logger = LoggerConfigurationFactory
|
||||
.Build(BuildConfig(null), "Site", "site-a", "node1")
|
||||
.WriteTo.Sink(sink)
|
||||
.CreateLogger();
|
||||
var logger = ScadaBridgeLogging.CreateLogger(
|
||||
BuildConfig(null), "Site", "site-a", "node1", new StringWriter(), lc => lc.WriteTo.Sink(sink));
|
||||
|
||||
var id = Guid.NewGuid();
|
||||
using (Serilog.Context.LogContext.PushProperty("ExecutionId", id))
|
||||
@@ -62,10 +58,8 @@ public class LoggerConfigurationTests
|
||||
public void MinimumLevel_Debug_AllowsDebugLogs()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
var logger = LoggerConfigurationFactory
|
||||
.Build(BuildConfig("Debug"), "Site", "site-a", "node1")
|
||||
.WriteTo.Sink(sink)
|
||||
.CreateLogger();
|
||||
var logger = ScadaBridgeLogging.CreateLogger(
|
||||
BuildConfig("Debug"), "Site", "site-a", "node1", new StringWriter(), lc => lc.WriteTo.Sink(sink));
|
||||
|
||||
logger.Debug("debug message");
|
||||
|
||||
@@ -78,10 +72,8 @@ public class LoggerConfigurationTests
|
||||
public void MinimumLevel_Absent_DefaultsToInformation()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
var logger = LoggerConfigurationFactory
|
||||
.Build(BuildConfig(null), "Central", "central", "node1")
|
||||
.WriteTo.Sink(sink)
|
||||
.CreateLogger();
|
||||
var logger = ScadaBridgeLogging.CreateLogger(
|
||||
BuildConfig(null), "Central", "central", "node1", new StringWriter(), lc => lc.WriteTo.Sink(sink));
|
||||
|
||||
logger.Debug("debug message");
|
||||
logger.Information("info message");
|
||||
@@ -101,7 +93,7 @@ public class LoggerConfigurationTests
|
||||
{
|
||||
var writer = new StringWriter();
|
||||
|
||||
var result = LoggerConfigurationFactory.ParseLevel("Informaiton", writer);
|
||||
var result = ScadaBridgeLogging.ParseLevel("Informaiton", writer);
|
||||
|
||||
Assert.Equal(LogEventLevel.Information, result);
|
||||
var warning = writer.ToString();
|
||||
@@ -116,8 +108,8 @@ public class LoggerConfigurationTests
|
||||
{
|
||||
var writer = new StringWriter();
|
||||
|
||||
var nullResult = LoggerConfigurationFactory.ParseLevel(null, writer);
|
||||
var blankResult = LoggerConfigurationFactory.ParseLevel(" ", writer);
|
||||
var nullResult = ScadaBridgeLogging.ParseLevel(null, writer);
|
||||
var blankResult = ScadaBridgeLogging.ParseLevel(" ", writer);
|
||||
|
||||
Assert.Equal(LogEventLevel.Information, nullResult);
|
||||
Assert.Equal(LogEventLevel.Information, blankResult);
|
||||
@@ -130,7 +122,7 @@ public class LoggerConfigurationTests
|
||||
{
|
||||
var writer = new StringWriter();
|
||||
|
||||
var result = LoggerConfigurationFactory.ParseLevel("Warning", writer);
|
||||
var result = ScadaBridgeLogging.ParseLevel("Warning", writer);
|
||||
|
||||
Assert.Equal(LogEventLevel.Warning, result);
|
||||
Assert.Empty(writer.ToString());
|
||||
@@ -141,7 +133,7 @@ public class LoggerConfigurationTests
|
||||
/// of truth for the Serilog floor, and the explicit <c>MinimumLevel.Is</c>
|
||||
/// call deliberately runs after <c>ReadFrom.Configuration(...)</c> so a
|
||||
/// <c>Serilog:MinimumLevel</c> entry is overridden. To make that precedence
|
||||
/// visible — instead of silently swallowed — <see cref="LoggerConfigurationFactory.Build(IConfiguration,string,string,string,TextWriter)"/>
|
||||
/// visible — instead of silently swallowed — <see cref="ScadaBridgeLogging.GovernMinimumLevel(IConfiguration,TextWriter)"/>
|
||||
/// writes a one-shot warning when both keys are present. The warning must
|
||||
/// name both values and point the operator at the documented key. When the
|
||||
/// Serilog key is absent the warning is silent.
|
||||
@@ -158,7 +150,7 @@ public class LoggerConfigurationTests
|
||||
})
|
||||
.Build();
|
||||
|
||||
LoggerConfigurationFactory.Build(configuration, "Central", "central", "node1", writer);
|
||||
using var _ = ScadaBridgeLogging.CreateLogger(configuration, "Central", "central", "node1", writer, null);
|
||||
|
||||
var warning = writer.ToString();
|
||||
Assert.Contains("warning", warning, StringComparison.OrdinalIgnoreCase);
|
||||
@@ -180,7 +172,7 @@ public class LoggerConfigurationTests
|
||||
})
|
||||
.Build();
|
||||
|
||||
LoggerConfigurationFactory.Build(configuration, "Central", "central", "node1", writer);
|
||||
using var _ = ScadaBridgeLogging.CreateLogger(configuration, "Central", "central", "node1", writer, null);
|
||||
|
||||
// No Serilog override -> no override-warning. (The ScadaBridge value is
|
||||
// a recognised level, so ParseLevel is silent too.)
|
||||
@@ -201,8 +193,7 @@ public class LoggerConfigurationTests
|
||||
public void Build_IncludesTheExecutionCaptureSink()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>()).Build();
|
||||
using var logger = LoggerConfigurationFactory.Build(configuration, "Site", "site-a", "node1", new StringWriter())
|
||||
.CreateLogger();
|
||||
using var logger = ScadaBridgeLogging.CreateLogger(configuration, "Site", "site-a", "node1", new StringWriter(), null);
|
||||
var id = Guid.NewGuid();
|
||||
var target = new CollectingTarget();
|
||||
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
using System.Diagnostics;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Serilog;
|
||||
using Serilog.Core;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.Host.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// ScadaBridge#94: the host logger moved from ScadaBridge's own <c>LoggerConfigurationFactory</c>
|
||||
/// onto the shared <c>AddZbSerilog</c> bootstrap (Telemetry.Serilog 0.2.0) with a minimum-level
|
||||
/// governor and a final <c>ConfigureLogger</c> hook. These tests pin the behaviour the old factory
|
||||
/// had, through the real pipeline: level governance (the ScadaBridge key outranks the Serilog key,
|
||||
/// namespace overrides still apply), the exact node-identity enrichers, trace correlation and the
|
||||
/// property set of a plain line. The standby filter is pinned in
|
||||
/// <see cref="StandbyHealthCheckLogNoiseTests"/> and the configured file sink in
|
||||
/// <see cref="SerilogSinkConfigTests"/>, both through the same pipeline.
|
||||
/// </summary>
|
||||
public class ScadaBridgeLoggingParityTests
|
||||
{
|
||||
private static IConfiguration Config(params (string Key, string Value)[] values) =>
|
||||
new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(values.ToDictionary(v => v.Key, v => (string?)v.Value))
|
||||
.Build();
|
||||
|
||||
private static Logger Create(
|
||||
IConfiguration configuration,
|
||||
InMemorySink sink,
|
||||
string nodeRole = "Site",
|
||||
string siteId = "site-a",
|
||||
string nodeHostname = "configured-node-hostname",
|
||||
TextWriter? writer = null) =>
|
||||
ScadaBridgeLogging.CreateLogger(
|
||||
configuration, nodeRole, siteId, nodeHostname, writer ?? new StringWriter(), lc => lc.WriteTo.Sink(sink));
|
||||
|
||||
/// <summary>
|
||||
/// Host-011: <c>ScadaBridge:Logging:MinimumLevel</c> is the floor even when
|
||||
/// <c>Serilog:MinimumLevel</c> asks for something more verbose. Fails if the governor stops
|
||||
/// running after <c>ReadFrom.Configuration</c> (the shared default ordering).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ScadaBridgeLevel_OutranksAMoreVerboseSerilogLevel()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
using var logger = Create(
|
||||
Config(("ScadaBridge:Logging:MinimumLevel", "Warning"), ("Serilog:MinimumLevel", "Verbose")),
|
||||
sink);
|
||||
|
||||
logger.Debug("debug");
|
||||
logger.Information("info");
|
||||
logger.Warning("warning");
|
||||
|
||||
var evt = Assert.Single(sink.LogEvents);
|
||||
Assert.Equal(LogEventLevel.Warning, evt.Level);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The governor never defers to the Serilog key: with the ScadaBridge key absent the floor is
|
||||
/// Information (the <see cref="LoggingOptions"/> default), not the configured Serilog Error.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ScadaBridgeKeyAbsent_FloorIsInformation_NotTheSerilogKey()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
using var logger = Create(Config(("Serilog:MinimumLevel:Default", "Error")), sink);
|
||||
|
||||
logger.Debug("debug");
|
||||
logger.Information("info");
|
||||
|
||||
var evt = Assert.Single(sink.LogEvents);
|
||||
Assert.Equal(LogEventLevel.Information, evt.Level);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Only the DEFAULT level is governed: a <c>Serilog:MinimumLevel:Override:*</c> namespace entry
|
||||
/// still raises that namespace's floor, as it did under the old factory.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void NamespaceOverrides_StillApply()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
using var logger = Create(
|
||||
Config(
|
||||
("ScadaBridge:Logging:MinimumLevel", "Debug"),
|
||||
("Serilog:MinimumLevel:Override:Noisy.Namespace", "Error")),
|
||||
sink);
|
||||
|
||||
logger.ForContext(Constants.SourceContextPropertyName, "Noisy.Namespace.Thing").Warning("noisy warning");
|
||||
logger.ForContext(Constants.SourceContextPropertyName, "Quiet.Namespace.Thing").Debug("quiet debug");
|
||||
|
||||
var evt = Assert.Single(sink.LogEvents);
|
||||
Assert.Equal("quiet debug", evt.RenderMessage());
|
||||
}
|
||||
|
||||
/// <summary>The override warning is written once per logger build, not per line.</summary>
|
||||
[Fact]
|
||||
public void OverrideWarning_IsOneShot()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
var writer = new StringWriter();
|
||||
using var logger = Create(
|
||||
Config(("ScadaBridge:Logging:MinimumLevel", "Warning"), ("Serilog:MinimumLevel", "Debug")),
|
||||
sink,
|
||||
writer: writer);
|
||||
|
||||
logger.Warning("one");
|
||||
logger.Warning("two");
|
||||
|
||||
var lines = writer.ToString().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||
Assert.Single(lines);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>NodeHostname</c> is the CONFIGURED <c>ScadaBridge:Node:NodeHostname</c>, not the machine
|
||||
/// name the shared bootstrap stamps, and <c>SiteId</c>/<c>NodeRole</c> are the configured values.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void IdentityEnrichers_AreTheConfiguredValues()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
const string hostname = "configured-node-hostname";
|
||||
Assert.NotEqual(hostname, Environment.MachineName); // positive control: the two differ
|
||||
using var logger = Create(Config(), sink, nodeRole: "Central", siteId: "central", nodeHostname: hostname);
|
||||
|
||||
logger.Information("line");
|
||||
|
||||
var evt = Assert.Single(sink.LogEvents);
|
||||
Assert.Equal("central", Scalar(evt, "SiteId"));
|
||||
Assert.Equal("Central", Scalar(evt, "NodeRole"));
|
||||
Assert.Equal(hostname, Scalar(evt, "NodeHostname"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The old factory stamped an empty <c>SiteId</c> verbatim; the shared bootstrap skips empty
|
||||
/// identity values. ScadaBridge keeps stamping it.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void EmptySiteId_IsStillStamped()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
using var logger = Create(Config(), sink, siteId: "");
|
||||
|
||||
logger.Information("line");
|
||||
|
||||
Assert.Equal("", Scalar(Assert.Single(sink.LogEvents), "SiteId"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A plain line carries exactly the three identity properties — no enricher was added or lost
|
||||
/// in the move (the trace enricher adds nothing outside an Activity, the redaction seam is inert).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void PlainLine_CarriesExactlyTheIdentityProperties()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
using var logger = Create(Config(), sink);
|
||||
|
||||
logger.Information("plain");
|
||||
|
||||
var keys = Assert.Single(sink.LogEvents).Properties.Keys.OrderBy(k => k, StringComparer.Ordinal);
|
||||
Assert.Equal(new[] { "NodeHostname", "NodeRole", "SiteId" }, keys);
|
||||
}
|
||||
|
||||
/// <summary>Inside an Activity the shared <c>TraceContextEnricher</c> stamps trace_id/span_id.</summary>
|
||||
[Fact]
|
||||
public void InsideAnActivity_TraceContextIsStamped()
|
||||
{
|
||||
var sink = new InMemorySink();
|
||||
using var logger = Create(Config(), sink);
|
||||
using var activity = new Activity("parity-test").SetIdFormat(ActivityIdFormat.W3C).Start();
|
||||
|
||||
logger.Information("traced");
|
||||
|
||||
var evt = Assert.Single(sink.LogEvents);
|
||||
Assert.Equal(activity.TraceId.ToHexString(), Scalar(evt, "trace_id"));
|
||||
Assert.Equal(activity.SpanId.ToHexString(), Scalar(evt, "span_id"));
|
||||
}
|
||||
|
||||
private static string? Scalar(LogEvent evt, string name) =>
|
||||
evt.Properties.TryGetValue(name, out var value) && value is ScalarValue { Value: var v } ? v?.ToString() : null;
|
||||
}
|
||||
@@ -50,7 +50,7 @@ public class SerilogAkkaLoggerTests : TestKit
|
||||
/// <summary>
|
||||
/// The system keeps Akka's default logger (TestKit's); each test that needs the bridge spawns a
|
||||
/// <see cref="SerilogAkkaLogger"/> over a capturing pipeline that mirrors the host's
|
||||
/// <c>LoggerConfigurationFactory</c> (<c>Enrich.FromLogContext</c> plus a node property).
|
||||
/// <c>ScadaBridgeLogging</c> (<c>Enrich.FromLogContext</c> plus a node property).
|
||||
/// </summary>
|
||||
public SerilogAkkaLoggerTests() : base("akka.loglevel = INFO")
|
||||
{
|
||||
|
||||
@@ -52,9 +52,9 @@ public class SerilogSinkConfigTests
|
||||
Assert.Contains("File", sinkNames);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the logger configuration factory applies the configured file sink.</summary>
|
||||
/// <summary>Verifies that the host logger (shared AddZbSerilog bootstrap) applies the configured file sink.</summary>
|
||||
[Fact]
|
||||
public void LoggerConfigurationFactory_AppliesConfiguredFileSink()
|
||||
public void ScadaBridgeLogging_AppliesConfiguredFileSink()
|
||||
{
|
||||
// A `Serilog` section in configuration must actually reach the built logger
|
||||
// via ReadFrom.Configuration — proving the sink set is configuration-driven.
|
||||
@@ -72,9 +72,8 @@ public class SerilogSinkConfigTests
|
||||
})
|
||||
.Build();
|
||||
|
||||
var logger = LoggerConfigurationFactory
|
||||
.Build(configuration, "Central", "central", "node1")
|
||||
.CreateLogger();
|
||||
var logger = ScadaBridgeLogging.CreateLogger(
|
||||
configuration, "Central", "central", "node1", new StringWriter(), null);
|
||||
|
||||
logger.Information("host-014 configured-sink probe");
|
||||
logger.Dispose();
|
||||
|
||||
@@ -38,10 +38,9 @@ public class StandbyHealthCheckLogNoiseTests
|
||||
})
|
||||
.Build();
|
||||
|
||||
return LoggerConfigurationFactory
|
||||
.Build(config, "Site", "site-a", "site-a-b")
|
||||
.WriteTo.Sink(sink)
|
||||
.CreateLogger();
|
||||
// The real host pipeline: the shared AddZbSerilog bootstrap plus ScadaBridge's hooks.
|
||||
return ScadaBridgeLogging.CreateLogger(
|
||||
config, "Site", "site-a", "site-a-b", new StringWriter(), lc => lc.WriteTo.Sink(sink));
|
||||
}
|
||||
|
||||
/// <summary>Emits one event shaped exactly like the framework's per-check line.</summary>
|
||||
@@ -155,6 +154,6 @@ public class StandbyHealthCheckLogNoiseTests
|
||||
{
|
||||
// Defensive: Serilog never hands the filter a null, but the predicate is internal
|
||||
// and reachable, and returning "suppress" for null would be the wrong default.
|
||||
Assert.False(LoggerConfigurationFactory.IsExpectedStandbyActiveNodeProbe(null!));
|
||||
Assert.False(ScadaBridgeLogging.IsExpectedStandbyActiveNodeProbe(null!));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user