feat(telemetry): 0.3.0 service.version default, ResourceAttributes, logs follow AddZbTelemetry OTLP (#55)

- service.version: null ServiceVersion now defaults to the entry assembly's
  AssemblyInformationalVersion (the family apps stamp the git SHA there); "" omits it.
- ResourceAttributes: extra Resource attributes on every signal; first-class keys
  (service.*, host.name, site.id, node.role) are reserved and rejected at startup.
- Logs over OTLP: AddZbTelemetry publishes its options in DI and AddZbSerilog's OTLP
  log sink follows them when its own options do not select Otlp, so
  <App>:Telemetry:Exporter=Otlp now switches logs along with metrics and traces, with
  the same endpoint and Resource. ExportLogs=false opts out.
- Ships the unpublished 0.2.1 review fixes, including the stricter OTLP endpoint check
  (scheme-less host:port rejected when Exporter=Otlp); no app config sets an endpoint.
- Tests 42 -> 74, incl. a loopback OTLP/gRPC receiver proving logs arrive with the
  Resource, and an ExportLogs=false case with a metrics positive control.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
Joseph Doherty
2026-11-12 20:58:59 -05:00
parent 616e913f3e
commit cfc7168ace
14 changed files with 639 additions and 34 deletions
@@ -49,7 +49,20 @@ internal static class ZbSerilogConfig
public static LoggerConfiguration Apply(
LoggerConfiguration loggerConfiguration,
ZbTelemetryOptions options,
IServiceProvider? serviceProvider)
IServiceProvider? serviceProvider) =>
Apply(loggerConfiguration, options, serviceProvider, registeredTelemetry: null);
/// <summary>
/// Full overload: <paramref name="registeredTelemetry"/> is the options an <c>AddZbTelemetry</c>
/// call registered in the same container (or <see langword="null"/>). The OTLP log sink follows
/// it when <paramref name="options"/> does not select OTLP itself — see
/// <see cref="ResolveLogExport"/>. Identity enrichers always come from <paramref name="options"/>.
/// </summary>
public static LoggerConfiguration Apply(
LoggerConfiguration loggerConfiguration,
ZbTelemetryOptions options,
IServiceProvider? serviceProvider,
ZbTelemetryOptions? registeredTelemetry)
{
ArgumentNullException.ThrowIfNull(loggerConfiguration);
ArgumentNullException.ThrowIfNull(options);
@@ -75,7 +88,10 @@ internal static class ZbSerilogConfig
ApplyRedaction(loggerConfiguration, serviceProvider);
}
ApplyOpenTelemetryExport(loggerConfiguration, options);
if (ResolveLogExport(options, registeredTelemetry) is { } export)
{
ApplyOpenTelemetryExport(loggerConfiguration, export);
}
return loggerConfiguration;
}
@@ -90,6 +106,33 @@ internal static class ZbSerilogConfig
internal static void ApplyRedaction(LoggerConfiguration loggerConfiguration, IServiceProvider serviceProvider) =>
loggerConfiguration.Enrich.With(new RedactionEnricher(serviceProvider));
/// <summary>
/// Chooses the options the OTLP log sink is built from, or <see langword="null"/> for no sink:
/// <list type="number">
/// <item><paramref name="serilogOptions"/> when it selects <see cref="ZbExporter.Otlp"/> itself
/// (the pre-0.3.0 behaviour; an app that builds its logger outside the host container, such as
/// ScadaBridge, passes the exporter here);</item>
/// <item>else the <c>AddZbTelemetry</c> registration in the same container when it selects
/// OTLP — so <c>&lt;App&gt;:Telemetry:Exporter=Otlp</c> switches logs along with metrics and
/// traces, with the identical Resource (scadaproj#55);</item>
/// <item>else none.</item>
/// </list>
/// Whichever is chosen, its <see cref="ZbTelemetryOptions.ExportLogs"/> = <see langword="false"/>
/// keeps logs local.
/// </summary>
internal static ZbTelemetryOptions? ResolveLogExport(
ZbTelemetryOptions serilogOptions,
ZbTelemetryOptions? registeredTelemetry)
{
ArgumentNullException.ThrowIfNull(serilogOptions);
var source = serilogOptions.Exporter == ZbExporter.Otlp
? serilogOptions
: registeredTelemetry is { Exporter: ZbExporter.Otlp } ? registeredTelemetry : null;
return source is { ExportLogs: true } ? source : null;
}
/// <summary>
/// Adds a <c>WriteTo.OpenTelemetry</c> log sink when an OTLP exporter is explicitly
/// selected (<see cref="ZbTelemetryOptions.Exporter"/> = <see cref="ZbExporter.Otlp"/>).
@@ -1,3 +1,4 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
@@ -14,6 +15,14 @@ namespace ZB.MOM.WW.Telemetry.Serilog;
/// <c>AddZbTelemetry</c> in the core package for that.
///
/// <para>
/// <b>OTLP logs (0.3.0+).</b> An OTLP log sink is added when the options passed here select
/// <c>Exporter = Otlp</c>, or otherwise when an <c>AddZbTelemetry</c> call in the same service
/// collection does — the sink then uses that registration's endpoint and Resource, so logs go where
/// metrics and traces go. <c>ZbTelemetryOptions.ExportLogs = false</c> on the chosen options keeps
/// logs local. Levels and the configuration-driven sinks are unaffected.
/// </para>
///
/// <para>
/// This method intentionally does <strong>not</strong> set the process-global
/// <see cref="Log.Logger"/> (via <c>CreateBootstrapLogger</c> or otherwise). Mutating
/// process-global state in a shared library causes "logger is already frozen" exceptions
@@ -119,7 +128,11 @@ public static class ZbSerilogExtensions
// enrichers in registration order, so a RedactionEnricher registered before
// ConfigureLogger would let hook-added enrichers stamp properties that reach every
// sink unredacted. Apply() is told there is no provider so it skips redaction here.
ZbSerilogConfig.Apply(loggerConfiguration, options, serviceProvider: null);
// The OTLP log sink follows the AddZbTelemetry registration in this container when
// these options do not select OTLP themselves (scadaproj#55). Resolved here, inside
// the AddSerilog callback, so the AddZbTelemetry/AddZbSerilog call order is irrelevant.
var registered = serviceProvider.GetService<ZbTelemetryRegistration>()?.Options;
ZbSerilogConfig.Apply(loggerConfiguration, options, serviceProvider: null, registered);
serilogOptions.ConfigureLogger?.Invoke(loggerConfiguration, serviceProvider);
@@ -29,6 +29,9 @@
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>ZB.MOM.WW.Telemetry.Serilog.Tests</_Parameter1>
</AssemblyAttribute>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>ZB.MOM.WW.Telemetry.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Reflection;
using OpenTelemetry.Resources;
namespace ZB.MOM.WW.Telemetry;
@@ -19,12 +20,70 @@ public static class ZbResource
public static string InstanceId =>
$"{System.Environment.MachineName}:{System.Environment.ProcessId}";
/// <summary>
/// Resource keys owned by first-class <see cref="ZbTelemetryOptions"/> members (or computed by
/// the library). <see cref="ZbTelemetryOptions.ResourceAttributes"/> may not set them.
/// </summary>
public static IReadOnlySet<string> ReservedAttributeKeys { get; } = new HashSet<string>(StringComparer.Ordinal)
{
"service.name",
"service.namespace",
"service.version",
"service.instance.id",
"host.name",
"site.id",
"node.role",
};
private static readonly Lazy<string?> EntryAssemblyVersion =
new(() => VersionOf(Assembly.GetEntryAssembly()));
/// <summary>
/// The <c>service.version</c> used when <see cref="ZbTelemetryOptions.ServiceVersion"/> is
/// <see langword="null"/>: the entry assembly's <c>AssemblyInformationalVersion</c> (the family
/// apps stamp the git SHA there), else its assembly version, else <see langword="null"/>
/// (attribute omitted). Computed once per process.
/// </summary>
public static string? DefaultServiceVersion => EntryAssemblyVersion.Value;
/// <summary>
/// Version string of <paramref name="assembly"/>: its <c>AssemblyInformationalVersion</c> when
/// present and non-blank, else its assembly version, else <see langword="null"/>.
/// </summary>
/// <param name="assembly">The assembly to read, typically the entry assembly.</param>
internal static string? VersionOf(Assembly? assembly)
{
if (assembly is null)
{
return null;
}
var informational = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
if (!string.IsNullOrWhiteSpace(informational))
{
return informational;
}
return assembly.GetName().Version?.ToString();
}
/// <summary>
/// The effective <c>service.version</c> for <paramref name="options"/>: the explicit value when
/// set (<c>""</c> means omit, returned as <see langword="null"/>), else
/// <paramref name="defaultVersion"/>.
/// </summary>
internal static string? ResolveServiceVersion(ZbTelemetryOptions options, string? defaultVersion) =>
options.ServiceVersion is null
? defaultVersion
: options.ServiceVersion.Length == 0 ? null : options.ServiceVersion;
/// <summary>
/// Returns a <see cref="ResourceBuilder"/> pre-populated with <c>service.name</c>,
/// <c>service.namespace</c>, <c>service.version</c>, <c>service.instance.id</c>,
/// <c>site.id</c>, <c>node.role</c>, and <c>host.name</c> (always
/// <see cref="System.Environment.MachineName"/>). Attributes with null values are omitted
/// from the Resource.
/// <c>site.id</c>, <c>node.role</c>, <c>host.name</c> (always
/// <see cref="System.Environment.MachineName"/>) and every
/// <see cref="ZbTelemetryOptions.ResourceAttributes"/> entry. Optional attributes with null
/// values are omitted; a null <c>ServiceVersion</c> defaults to <see cref="DefaultServiceVersion"/>.
/// </summary>
/// <param name="options">The telemetry options describing the service identity.</param>
public static ResourceBuilder Build(ZbTelemetryOptions options) =>
@@ -36,26 +95,44 @@ public static class ZbResource
/// Serilog OTLP log sink — derives its attributes from this one map, so logs can never drift
/// from metrics/traces. Required attributes (<c>service.name</c>, <c>service.namespace</c>,
/// <c>service.instance.id</c>, <c>host.name</c>) are always present; optional ones
/// (<c>service.version</c>, <c>site.id</c>, <c>node.role</c>) are included only when the
/// corresponding option is non-null/non-empty, matching the Resource's omission rules.
/// (<c>site.id</c>, <c>node.role</c>) are included only when the corresponding option is
/// non-null/non-empty; <c>service.version</c> follows <see cref="ZbTelemetryOptions.ServiceVersion"/>
/// (null = <see cref="DefaultServiceVersion"/>, <c>""</c> = omitted); every
/// <see cref="ZbTelemetryOptions.ResourceAttributes"/> entry is included.
/// </summary>
/// <param name="options">The telemetry options describing the service identity.</param>
/// <returns>The canonical attribute map carried by all three signals.</returns>
public static IReadOnlyDictionary<string, object> BuildAttributes(ZbTelemetryOptions options)
public static IReadOnlyDictionary<string, object> BuildAttributes(ZbTelemetryOptions options) =>
BuildAttributes(options, DefaultServiceVersion);
/// <summary>
/// <see cref="BuildAttributes(ZbTelemetryOptions)"/> with an explicit automatic
/// <c>service.version</c> (the test seam for the entry-assembly default).
/// </summary>
internal static IReadOnlyDictionary<string, object> BuildAttributes(ZbTelemetryOptions options, string? defaultVersion)
{
ArgumentNullException.ThrowIfNull(options);
var attributes = new Dictionary<string, object>(StringComparer.Ordinal)
{
["service.name"] = options.ServiceName,
["service.namespace"] = options.ServiceNamespace,
["service.instance.id"] = InstanceId,
["host.name"] = System.Environment.MachineName,
};
var attributes = new Dictionary<string, object>(StringComparer.Ordinal);
if (!string.IsNullOrEmpty(options.ServiceVersion))
// Caller-supplied extras first; the first-class keys below are reserved (the validator
// rejects them in ResourceAttributes), so nothing here can be shadowed.
if (options.ResourceAttributes is { } extras)
{
attributes["service.version"] = options.ServiceVersion;
foreach (var (key, value) in extras)
{
attributes[key] = value;
}
}
attributes["service.name"] = options.ServiceName;
attributes["service.namespace"] = options.ServiceNamespace;
attributes["service.instance.id"] = InstanceId;
attributes["host.name"] = System.Environment.MachineName;
if (ResolveServiceVersion(options, defaultVersion) is { } version)
{
attributes["service.version"] = version;
}
if (!string.IsNullOrEmpty(options.SiteId))
@@ -48,6 +48,11 @@ public static class ZbTelemetryExtensions
// same fail-fast treatment (Telemetry-011).
ValidateRequired(options, nameof(options));
// Published for the Serilog companion: AddZbSerilog's OTLP log sink follows this
// registration's exporter/endpoint/identity so that logs go where metrics and traces go
// without the app repeating the settings (scadaproj#55).
services.AddSingleton(new ZbTelemetryRegistration(options));
services.AddOpenTelemetry()
.ConfigureResource(rb => ZbResource.Configure(rb, options))
.WithMetrics(metrics =>
@@ -35,8 +35,11 @@ public sealed class ZbTelemetryOptions
public string ServiceNamespace { get; set; } = "ZB.MOM.WW";
/// <summary>
/// Optional. Populate from <c>AssemblyInformationalVersion</c>.
/// Populates OTel Resource <c>service.version</c>.
/// Populates OTel Resource <c>service.version</c>. <see langword="null"/> (the default) means
/// <em>automatic</em>: the entry assembly's <c>AssemblyInformationalVersion</c> (every family app
/// stamps the git SHA there, e.g. <c>1.0.0+424db155…</c>), falling back to its assembly version
/// (see <see cref="ZbResource.DefaultServiceVersion"/>). Set a value to override it; set
/// <c>""</c> to omit the attribute. Before 0.3.0 <see langword="null"/> omitted it.
/// </summary>
public string? ServiceVersion { get; set; }
@@ -52,6 +55,17 @@ public sealed class ZbTelemetryOptions
/// </summary>
public string? NodeRole { get; set; }
/// <summary>
/// Extra OTel Resource attributes carried by every signal (metrics, traces and the Serilog OTLP
/// log sink), e.g. <c>["otopcua.cluster.id"] = "c1"</c>. Values must be non-null; use strings,
/// booleans, integers or doubles. Keys owned by a first-class option — <c>service.name</c>,
/// <c>service.namespace</c>, <c>service.version</c>, <c>service.instance.id</c>,
/// <c>host.name</c>, <c>site.id</c>, <c>node.role</c> — are rejected at startup; set the option
/// instead (<see cref="ZbResource.ReservedAttributeKeys"/>).
/// </summary>
public IDictionary<string, object> ResourceAttributes { get; set; } =
new Dictionary<string, object>(StringComparer.Ordinal);
/// <summary>
/// App-specific Meter names to register with the OTel MeterProvider. Standard instrumentation
/// meters are added automatically (ASP.NET Core, HttpClient, runtime, process).
@@ -73,4 +87,13 @@ public sealed class ZbTelemetryOptions
/// OTLP gRPC endpoint, e.g. <c>"http://collector:4317"</c>.
/// </summary>
public string? OtlpEndpoint { get; set; }
/// <summary>
/// When <see cref="Exporter"/> = <see cref="ZbExporter.Otlp"/>, also export logs to the same
/// <see cref="OtlpEndpoint"/> through the <c>ZB.MOM.WW.Telemetry.Serilog</c> OTLP log sink.
/// Default <see langword="true"/>. Set <see langword="false"/> to keep logs on the local sinks
/// only while metrics and traces go to OTLP. Ignored for the Prometheus exporter, and ignored
/// when the Serilog companion package is not used.
/// </summary>
public bool ExportLogs { get; set; } = true;
}
@@ -20,6 +20,8 @@ internal static class ZbTelemetryOptionsValidator
{
ArgumentNullException.ThrowIfNull(options);
ValidateResourceAttributes(options, paramName);
if (options.Exporter != ZbExporter.Otlp)
{
return;
@@ -46,4 +48,36 @@ internal static class ZbTelemetryOptionsValidator
paramName);
}
}
private static void ValidateResourceAttributes(ZbTelemetryOptions options, string paramName)
{
if (options.ResourceAttributes is not { Count: > 0 } extras)
{
return;
}
foreach (var (key, value) in extras)
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException(
"ZbTelemetryOptions.ResourceAttributes contains a blank key.", paramName);
}
if (ZbResource.ReservedAttributeKeys.Contains(key))
{
throw new ArgumentException(
$"ZbTelemetryOptions.ResourceAttributes may not set '{key}'; it is owned by a " +
"first-class option (ServiceName, ServiceNamespace, ServiceVersion, SiteId, NodeRole) " +
"or computed by the library.",
paramName);
}
if (value is null)
{
throw new ArgumentException(
$"ZbTelemetryOptions.ResourceAttributes['{key}'] is null.", paramName);
}
}
}
}
@@ -0,0 +1,9 @@
namespace ZB.MOM.WW.Telemetry;
/// <summary>
/// The options an <c>AddZbTelemetry</c> call registered, published in DI so the Serilog companion
/// (<c>AddZbSerilog</c>) can send logs to the same OTLP endpoint with the same Resource as metrics
/// and traces. Internal: the companion assembly sees it through <c>InternalsVisibleTo</c>.
/// </summary>
/// <param name="Options">The validated options passed to <c>AddZbTelemetry</c>.</param>
internal sealed record ZbTelemetryRegistration(ZbTelemetryOptions Options);