1786bab0a0
Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
73 lines
2.7 KiB
C#
73 lines
2.7 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Serilog;
|
|
using Serilog.Core;
|
|
using Serilog.Events;
|
|
|
|
namespace ZB.MOM.WW.Telemetry.Serilog.Tests;
|
|
|
|
/// <summary>Regression tests for Telemetry-009 and Telemetry-010 (scadaproj#48).</summary>
|
|
public sealed class ReviewP3Tests
|
|
{
|
|
private sealed class MaskApiKey : ILogRedactor
|
|
{
|
|
public void Redact(IDictionary<string, object?> properties)
|
|
{
|
|
if (properties.ContainsKey("apiKey")) properties["apiKey"] = "***";
|
|
}
|
|
}
|
|
|
|
private sealed class NoOpRedactor : ILogRedactor
|
|
{
|
|
public void Redact(IDictionary<string, object?> properties) { }
|
|
}
|
|
|
|
private sealed class CaptureSink : ILogEventSink
|
|
{
|
|
public List<LogEvent> Events { get; } = [];
|
|
public void Emit(LogEvent logEvent) => Events.Add(logEvent);
|
|
}
|
|
|
|
[Fact]
|
|
public void Properties_stamped_by_ConfigureLogger_enrichers_are_redacted()
|
|
{
|
|
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });
|
|
builder.Services.AddSingleton<ILogRedactor>(new MaskApiKey());
|
|
var sink = new CaptureSink();
|
|
builder.AddZbSerilog(
|
|
o => o.ServiceName = "t",
|
|
s => s.ConfigureLogger = (lc, _) => lc.Enrich.WithProperty("apiKey", "s3cret").WriteTo.Sink(sink));
|
|
|
|
using var host = builder.Build();
|
|
host.Services.GetRequiredService<ILogger>().Information("hello");
|
|
|
|
var evt = Assert.Single(sink.Events);
|
|
Assert.Equal("***", ((ScalarValue)evt.Properties["apiKey"]).Value);
|
|
}
|
|
|
|
[Fact]
|
|
public void Dictionary_keys_that_print_identically_are_all_kept()
|
|
{
|
|
var provider = new ServiceCollection().AddSingleton<ILogRedactor>(new NoOpRedactor()).BuildServiceProvider();
|
|
var sink = new CaptureSink();
|
|
var cfg = new LoggerConfiguration();
|
|
ZbSerilogConfig.Apply(cfg, new ZbTelemetryOptions { ServiceName = "t" }, provider);
|
|
using var logger = cfg.WriteTo.Sink(sink).CreateLogger();
|
|
|
|
var map = new Dictionary<DateTime, string>
|
|
{
|
|
[new DateTime(2026, 1, 1, 12, 0, 0, 100)] = "first",
|
|
[new DateTime(2026, 1, 1, 12, 0, 0, 200)] = "second",
|
|
};
|
|
logger.Information("{Map}", map);
|
|
|
|
var dict = Assert.IsType<DictionaryValue>(Assert.Single(sink.Events).Properties["Map"]);
|
|
Assert.Equal(2, dict.Elements.Count);
|
|
Assert.Equal(
|
|
new[] { "first", "second" },
|
|
dict.Elements.Select(e => (string)((ScalarValue)e.Value).Value!).Order(StringComparer.Ordinal));
|
|
Assert.Equal(2, dict.Elements.Select(e => e.Key.Value).Distinct().Count());
|
|
}
|
|
}
|