Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Observability/ExecutionLogContextTests.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

131 lines
6.1 KiB
C#

using System.Collections.Concurrent;
using Newtonsoft.Json;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.InboundApi;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Instance;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.ScriptExecution;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Commons.Observability;
namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Observability;
/// <summary>
/// ScadaBridge#56: which messages name the execution they serve, and what pushing one does to a
/// LogContext-enriched logger.
/// </summary>
public class ExecutionLogContextTests
{
private static readonly DateTimeOffset Now = DateTimeOffset.UtcNow;
private static readonly Guid Id = Guid.NewGuid();
private sealed class CaptureSink : ILogEventSink
{
public ConcurrentQueue<LogEvent> Events { get; } = new();
public void Emit(LogEvent logEvent) => Events.Enqueue(logEvent);
}
/// <summary>Every correlated message, built with <see cref="Id"/> on its execution field.</summary>
/// <returns>The messages.</returns>
public static TheoryData<object> CorrelatedMessages() => new()
{
new SetStaticAttributeCommand("c", "i", "a", "v", Now, SourceExecutionId: Id),
new AttributeValueChanged("i", "p", "a", 1, "Good", Now, SourceExecutionId: Id),
new ScriptCallRequest("s", null, 0, "c", ParentExecutionId: Id),
new RouteToCallRequest("c", "i", "s", null, Now, ParentExecutionId: Id),
new RouteToGetAttributesRequest("c", "i", ["a"], Now, ParentExecutionId: Id),
new RouteToSetAttributesRequest("c", "i", new Dictionary<string, string>(), Now, ParentExecutionId: Id),
new RouteToWaitForAttributeRequest("c", "i", "a", null, TimeSpan.FromSeconds(1), Now, ParentExecutionId: Id),
new GetAttributeRequest("c", "i", "a", Now, SourceExecutionId: Id),
new WaitForAttributeRequest("c", "i", "a", null, null, TimeSpan.FromSeconds(1), Now, SourceExecutionId: Id),
new WriteAttributeBatchRequest("c", "i", new Dictionary<string, string?>(), null, null, Now, SourceExecutionId: Id),
new WriteTagRequest("c", "conn", "tag", 1, Now, SourceExecutionId: Id),
new WriteTagBatchRequest("c", "conn", new Dictionary<string, object?>(), null, null, Now, SourceExecutionId: Id),
};
/// <summary>Each correlated message reports the execution id it was built with.</summary>
/// <param name="message">The message.</param>
[Theory]
[MemberData(nameof(CorrelatedMessages))]
public void CorrelatedMessage_ReportsItsExecutionId(object message)
=> Assert.Equal(Id, Assert.IsAssignableFrom<IExecutionCorrelated>(message).CorrelatedExecutionId);
/// <summary>
/// The correlation member is an explicit interface implementation: it adds nothing to the
/// serialized shape, so the wire is unchanged.
/// </summary>
/// <param name="message">The message.</param>
[Theory]
[MemberData(nameof(CorrelatedMessages))]
public void CorrelatedMessage_SerializesNoExtraMember(object message)
=> Assert.DoesNotContain(nameof(IExecutionCorrelated.CorrelatedExecutionId), JsonConvert.SerializeObject(message));
/// <summary>An inferred writer (the trace arm's device-echo heuristic) is not stamped onto log lines.</summary>
[Fact]
public void InferredValueChange_NamesNoExecution()
{
IExecutionCorrelated inferred = new AttributeValueChanged(
"i", "p", "a", 1, "Good", Now, SourceExecutionId: Id, Trace: true, SourceExecutionInferred: true);
Assert.Null(inferred.CorrelatedExecutionId);
}
/// <summary>A message that names no execution - or is not correlated at all - pushes nothing.</summary>
[Fact]
public void PushFor_NothingToStamp_ReturnsNull()
{
Assert.Null(ExecutionLogContext.PushFor(new WriteTagRequest("c", "conn", "tag", 1, Now)));
Assert.Null(ExecutionLogContext.PushFor("not a message"));
Assert.Null(ExecutionLogContext.PushFor(null));
Assert.Null(ExecutionLogContext.Push(null));
}
/// <summary>Lines inside the scope carry the id, lines after it do not, and a nested push wins.</summary>
[Fact]
public void PushFor_StampsLinesInsideTheScope_AndTheInnermostWins()
{
var sink = new CaptureSink();
var log = new LoggerConfiguration().Enrich.FromLogContext().WriteTo.Sink(sink).CreateLogger();
var child = Guid.NewGuid();
using (ExecutionLogContext.PushFor(new ScriptCallRequest("s", null, 0, "c", ParentExecutionId: Id)))
{
log.Information("parent");
using (ExecutionLogContext.Push(child))
log.Information("child");
}
log.Information("outside");
var events = sink.Events.ToList();
Assert.Equal(Id.ToString(), events[0].Properties[ExecutionLogContext.ExecutionIdProperty].ToString().Trim('"'));
Assert.Equal(child.ToString(), events[1].Properties[ExecutionLogContext.ExecutionIdProperty].ToString().Trim('"'));
Assert.False(events[2].Properties.ContainsKey(ExecutionLogContext.ExecutionIdProperty));
}
/// <summary>
/// ScadaBridge#120: <see cref="ExecutionLogContext.Current"/> mirrors the pushed id, follows
/// nesting, and is restored when each push is disposed (twice is harmless).
/// </summary>
[Fact]
public void Current_TracksPushes_AndIsRestoredOnDispose()
{
var outer = Guid.NewGuid();
var inner = Guid.NewGuid();
Assert.Null(ExecutionLogContext.Current);
var a = ExecutionLogContext.Push(outer);
Assert.Equal(outer, ExecutionLogContext.Current);
var b = ExecutionLogContext.Push(inner);
Assert.Equal(inner, ExecutionLogContext.Current);
Assert.Null(ExecutionLogContext.Push(null)); // a null push changes nothing
Assert.Equal(inner, ExecutionLogContext.Current);
b!.Dispose();
b.Dispose();
Assert.Equal(outer, ExecutionLogContext.Current);
a!.Dispose();
Assert.Null(ExecutionLogContext.Current);
}
}