Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Observability/ExecutionLogCaptureTests.cs
T
Joseph Doherty c810bd0f7c feat(logging): bridge Akka logging to Serilog and copy traced runs' node-log lines into the Flow Debugger (ScadaBridge#120, #56)
#120: Akka ILoggingAdapter lines used to bypass Serilog and go to stdout only.
- BuildHocon sets akka.loggers = [Host.Actors.SerilogAkkaLogger] and keeps akka.loglevel = INFO,
  so Akka Debug chatter is still filtered at the adapter. The INFO+ lines that used to reach
  stdout now go through the Serilog pipeline instead, with no extra volume.
- Lines reach the file sinks with the node enrichers. SourceContext is the logging class's full
  name, AkkaSource is the actor path, Akka's own timestamp is kept, and format arguments become
  structured properties.
- The Akka logger actor writes on its own thread, after the logging actor's LogContext is gone.
  To keep the ExecutionId, the two DCL actors log through ExecutionAwareLogging.GetLogger(Context),
  which records ExecutionLogContext.Current (a new AsyncLocal mirror of the pushed id) in an
  ExecutionTaggedLogMessage. The logger actor pushes that id again while it writes the line.

#56 remainder (coordinator decision: no replicated schema change):
- The host pipeline gains ExecutionLogCaptureSink.
- While a run is traced, its step logger registers its ExecutionId: the site ScriptLogger from the
  launcher (plus each inline CallShared child id), and the central InboundScriptLogger from the
  executor.
- Each tagged line becomes a ScriptLog row with LogSource "node" and the new
  ScriptTraceExtra.LogCategory.
- The rows count against the existing MaxLogLinesPerRun cap, are clipped at 2 000 chars, ride the
  low-priority collector lane and pass the same redactor. Untraced runs cost one volatile read.
- Lines are never copied twice. The step loggers' own forwards run inside
  ExecutionLogCapture.Suppress(), and the sink suppresses itself while it calls a target. The
  registration is declared inside the launcher's and executor's try, so it ends before the catch
  blocks log the outcome, and FlushDropped closes it.
- FlowGraphBuilder lists node lines in FlowGraph.NodeLogs and never folds them onto a step.
- The Flow Debugger shows them in a Node log card (FlowNodeLogPanel): grouped per execution under
  its run step, with an All | Warn + filter. Live and Replay both read the same rows, so site
  scope and role rules apply unchanged.
- CLI --show-logs prints them as a trailing block.

Tests: Commons ExecutionLogCaptureTests, ExecutionLogContext.Current, FlowGraphBuilder node lines.
SiteRuntime NodeLogCaptureTests covers cross-actor capture via the launcher, untraced runs
capturing nothing, no double capture of script and runtime lines or of the launcher failure line,
the shared cap, collector redaction, shared-script child ids and FlushDropped closing capture.
InboundNodeLogCaptureTests covers the central path. DCL ExecutionAwareLoggingTests covers the
DataConnectionActor write-path Debug line being tagged and an uncorrelated line not being tagged.
Host SerilogAkkaLoggerTests covers mapping, the ExecutionId crossing the logger hop, HOCON,
ActorSystem boot and the Akka line reaching a traced run's step log end to end. Host
LoggerConfigurationTests checks that the sink is wired. bUnit FlowNodeLogPanelTests and a CLI
projection test cover the UI and CLI. Every new assertion was mutation-proven.

Docs: step-logs design section 12, Component-SiteRuntime, CentralUI, InboundAPI, Host, CLI README,
CLAUDE.md.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-10 06:12:34 -05:00

149 lines
5.6 KiB
C#

using System.Collections.Concurrent;
using Serilog;
using ZB.MOM.WW.ScadaBridge.Commons.Observability;
namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Observability;
/// <summary>
/// ScadaBridge#56: the per-execution sink copies a line to the target registered for the line's
/// <c>ExecutionId</c> — and to nothing else. Each test uses fresh ids, because the registry is
/// process-wide and other tests may register concurrently.
/// </summary>
public class ExecutionLogCaptureTests
{
private sealed class Target : IExecutionLogTarget
{
public ConcurrentQueue<CapturedLogLine> Lines { get; } = new();
public Action<CapturedLogLine>? OnCapture { get; init; }
public void Capture(CapturedLogLine line)
{
Lines.Enqueue(line);
OnCapture?.Invoke(line);
}
}
private static Serilog.ILogger Node() => new LoggerConfiguration()
.MinimumLevel.Information()
.Enrich.FromLogContext()
.WriteTo.Sink(new ExecutionLogCaptureSink())
.CreateLogger();
/// <summary>A line tagged with a registered id reaches its target with level, category, text, exception and time.</summary>
[Fact]
public void TaggedLine_ReachesItsTarget()
{
var node = Node().ForContext("SourceContext", "Acme.InstanceActor");
var id = Guid.NewGuid();
var target = new Target();
using var registration = ExecutionLogCapture.Register(id, target);
using (ExecutionLogContext.Push(id))
node.Warning(new InvalidOperationException("bad"), "wrote {Tag}", "T1");
var line = Assert.Single(target.Lines);
Assert.Equal("warn", line.Level);
Assert.Equal("Acme.InstanceActor", line.Category);
Assert.Equal("wrote \"T1\"", line.Message);
Assert.Equal("bad", line.Exception!.Message);
Assert.Equal(DateTimeKind.Utc, line.OccurredAtUtc.Kind);
Assert.True(ExecutionLogCapture.HasTargets);
}
/// <summary>Untagged lines, lines of another execution, and lines below the node's level are not captured.</summary>
[Fact]
public void UntaggedOrOtherOrFilteredLines_AreNotCaptured()
{
var node = Node();
var id = Guid.NewGuid();
var target = new Target();
using var registration = ExecutionLogCapture.Register(id, target);
node.Information("untagged");
using (ExecutionLogContext.Push(Guid.NewGuid()))
node.Information("other execution");
using (ExecutionLogContext.Push(id))
node.Debug("below the node minimum");
Assert.Empty(target.Lines);
}
/// <summary>A line written inside <see cref="ExecutionLogCapture.Suppress"/> (already a trace row) is skipped.</summary>
[Fact]
public void SuppressedLine_IsNotCaptured()
{
var node = Node();
var id = Guid.NewGuid();
var target = new Target();
using var registration = ExecutionLogCapture.Register(id, target);
using (ExecutionLogContext.Push(id))
{
using (ExecutionLogCapture.Suppress())
node.Information("already a row");
node.Information("captured");
}
Assert.Equal("captured", Assert.Single(target.Lines).Message);
}
/// <summary>A target that logs for the same execution while capturing does not loop back into itself.</summary>
[Fact]
public void TargetThatLogs_DoesNotRecapture()
{
var node = Node();
var id = Guid.NewGuid();
// Logs once only, so a broken guard fails this test instead of overflowing the stack.
var logged = 0;
var target = new Target { OnCapture = _ => { if (Interlocked.Increment(ref logged) == 1) node.Warning("emit failed"); } };
using var registration = ExecutionLogCapture.Register(id, target);
using (ExecutionLogContext.Push(id))
node.Information("first");
Assert.Equal("first", Assert.Single(target.Lines).Message);
}
/// <summary>A line logged on another thread that re-pushed the id (an actor serving the run) is captured.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task LineOnAnotherThread_WithTheIdRepushed_IsCaptured()
{
var node = Node();
var id = Guid.NewGuid();
var target = new Target();
using var registration = ExecutionLogCapture.Register(id, target);
await Task.Factory.StartNew(() =>
{
using (ExecutionLogContext.Push(id))
node.Information("from an actor thread");
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
Assert.Equal("from an actor thread", Assert.Single(target.Lines).Message);
}
/// <summary>Disposing removes the registration; a duplicate registration is ignored and its disposal harmless.</summary>
[Fact]
public void Dispose_Unregisters_AndDuplicateIsIgnored()
{
var node = Node();
var id = Guid.NewGuid();
var first = new Target();
var second = new Target();
var registration = ExecutionLogCapture.Register(id, first);
ExecutionLogCapture.Register(id, second).Dispose(); // duplicate: no-op, must not remove the first
Assert.True(ExecutionLogCapture.TryGetTarget(id, out var found));
Assert.Same(first, found);
registration.Dispose();
registration.Dispose();
Assert.False(ExecutionLogCapture.TryGetTarget(id, out _));
using (ExecutionLogContext.Push(id))
node.Information("after");
Assert.Empty(first.Lines);
Assert.Empty(second.Lines);
}
}