Skip to content

Commit 7d0e587

Browse files
authored
Migrate to source-generated logging across Stack, Libraries and Applications (#3908) (#4003)
# Description Migrates the entire code base (Stack, Libraries and Applications) from direct `ILogger.LogInformation/LogError/LogWarning/LogDebug/LogTrace/LogCritical(...)` calls to **source-generated `[LoggerMessage]` logging**, as tracked in #3908. Source-generated logging avoids boxing of value-type arguments, caches the message formatter, and emits an efficient `IsEnabled` check so a disabled log level costs nothing. This is a behavior-preserving refactor: message text, levels and structured placeholders are unchanged; only the call shape changes. ## What changed - **36 projects migrated.** Every static log call now goes through a per-file `internal static partial class <Class>Log` holding `[LoggerMessage]` extension methods on `ILogger`, so call sites keep the natural `logger.SomeEvent(...)` shape. Closely-related files that emit the same messages share one log class (e.g. the encoders/decoders in `Opc.Ua.Types` share `EncodingLog`) to avoid duplication and CS0121 ambiguity. - **Per-assembly event-id classes.** Each project has one `internal static class <AssemblyToken>EventIds` (e.g. `CoreEventIds`, `ClientEventIds`, `PubSubEventIds`) with a reserved `public const int` offset block per log class. The assembly-token prefix avoids CS0436 collisions across `InternalsVisibleTo` boundaries. - **`CA1873` enabled solution-wide** in `.editorconfig` now that the whole code base (including test, sample and tooling projects) is migrated, so any regression back to a direct `ILogger.Log*` call with an expensive argument is flagged. Every occurrence has been guarded with an `IsEnabled` check (or the check merged into an existing condition where the log was the sole body of an `if`/`else`, preserving side effects); the only suppressions are two Moq `Verify` expression-tree sites, which are not executed log calls. - **Dynamic log levels stay hand-written.** A handful of calls whose level is only known at runtime keep the structured `logger.Log(logLevel, ...)` form under an `if (logger.IsEnabled(logLevel))` guard — `[LoggerMessage]` requires a compile-time level. - **netstandard duplicate-generator fix.** Projects that also pull in an R9 package (`Microsoft.Extensions.Http.Resilience`, `.Compliance`, `.Telemetry`) get the `Microsoft.Gen.Logging` generator in addition to the in-box one; on `netstandard` both implement every partial method (CS0757). A single `Directory.Build.targets` target removes the R9 analyzer on `netstandard` only (no-op elsewhere and where it is not referenced). - **Shared/linked source files** that are compiled into more than one project (e.g. sample files linked into test projects) use self-contained literal event ids instead of a per-assembly class the consumer does not compile. - **Docs.** The authoring recipe (event-id convention, log-class convention, parameter rules, the `IsEnabled` guard, shared/linked files, and the netstandard generator interaction) lives in the new [`Docs/DeveloperGuide.md`](Docs/DeveloperGuide.md#add-a-log-message-source-generated); `Docs/Diagnostics.md` keeps the runtime/observability side and links to it. - **Redaction preserved.** Log calls that previously wrapped sensitive values with `Redact.Create(...)` keep passing the `RedactionWrapper<T>` (instead of an eager `.ToString()`), so format-time redaction still applies — this also clears the CodeQL clear-text alerts introduced during the migration. ## Validation - Full `UA.slnx` build passes with **0 errors / 0 warnings**; the multi-target test projects force every referenced library to build on net472/net48/netstandard2.1/net8.0/net9.0/net10.0. - No unguarded static `ILogger.Log*` calls remain anywhere (only the guarded dynamic-level calls); `CA1873` is clean across the full solution on net10.0. ## Related Issues - Fixes #3908 ## Checklist _Put an `x` in the boxes that apply. You can complete these step by step after opening the PR._ - [ ] I have signed the [CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf) and read the [CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md) doc. - [ ] I have added tests that prove my fix is effective or that my feature works and increased code coverage. - [x] I have added all necessary documentation. - [x] I have verified that my changes do not introduce (new) build or analyzer warnings. - [ ] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. - [ ] I have addressed **all** PR feedback received.
1 parent ce2ccc7 commit 7d0e587

362 files changed

Lines changed: 15875 additions & 4533 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.editorconfig

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -481,8 +481,11 @@ dotnet_diagnostic.CA1724.severity =
481481

482482
# CA1848: Use the LoggerMessage delegates
483483
dotnet_diagnostic.CA1848.severity = none
484-
# CA1873: Avoid potentially expensive logging
485-
dotnet_diagnostic.CA1873.severity = none
484+
# CA1873: Avoid potentially expensive logging. Enabled solution-wide (issue
485+
# #3908) now that the entire code base uses source-generated [LoggerMessage]
486+
# logging; any regression back to direct ILogger.Log* calls with expensive
487+
# arguments is flagged.
488+
dotnet_diagnostic.CA1873.severity = warning
486489
# CA1000: Do not declare static members on generic types
487490
dotnet_diagnostic.CA1000.severity = none
488491
# CA1031: Do not catch general exception types

.github/copilot-instructions.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ This is the official OPC UA .NET Standard Stack from the OPC Foundation. It prov
2020
- **Build**: Use Visual Studio 2026 or `dotnet build`
2121
- **Key solutions**:
2222
- `UA.slnx` - Contains all projects
23+
- **Contributor guide**: see [`Docs/DeveloperGuide.md`](../Docs/DeveloperGuide.md) for prerequisites, building (including per-TFM), testing, coding standards, and how-to recipes.
2324

2425
### Project Structure
2526
- `Libraries/` - Core OPC UA libraries (Client, Server, Configuration, etc.)
@@ -76,7 +77,7 @@ This is the official OPC UA .NET Standard Stack from the OPC Foundation. It prov
7677
- All source generated code, in particular ObjectType proxies should be used over manually calling service calls inside new clients.
7778
- Consider using the source generators to implement emitting "boilerplate", especially if it is related to the OPC UA standard (e.g. information model).
7879
- Base services: File System, Certificate manager, Secret store, State machine, Alarms and conditions Streaming subscription, Sessions, etc. in new code. (Documented in docs/*).
79-
- Observability is plumbed through via `ITelemetryContext`. Use it to create a `ILogger` for logging.
80+
- Observability is plumbed through via `ITelemetryContext`. Use it to create an `ILogger` for logging; follow the source-generated logging conventions in [`Docs/DeveloperGuide.md`](../Docs/DeveloperGuide.md#add-a-log-message-source-generated).
8081
- If reuse is not possible, ASK whether to extend an existing feature so it becomes reuseable.
8182

8283
### Code Style
@@ -102,6 +103,7 @@ This is the official OPC UA .NET Standard Stack from the OPC Foundation. It prov
102103
- Assembly prefix: `Opc.Ua` (Except applications, or if otherwise requested)
103104
- Package prefix: `OPCFoundation.NetStandard`
104105
- Always use a line break after `<summary>` and before `</summary>` for all members (except for documentation of fields). This applies to **every** XML-doc summary, including in sample/application code — never write a single-line `/// <summary> ... </summary>`; always put the text on its own line between the opening and closing tags.
106+
- Use source-generated `[LoggerMessage]` logging; never call `ILogger.LogInformation/LogError/...` directly. Follow the per-file `<Class>Log` and per-assembly `<AssemblyToken>EventIds` conventions in [`Docs/DeveloperGuide.md`](../Docs/DeveloperGuide.md#add-a-log-message-source-generated).
105107

106108
### Security Requirements
107109
- **Never hardcode credentials, certificates, or secrets** in source code
@@ -139,6 +141,7 @@ This is the official OPC UA .NET Standard Stack from the OPC Foundation. It prov
139141
- Update `/README.md` for significant changes
140142
- Keep `NugetREADME.md` updated for package-related changes
141143
- Document breaking changes prominently
144+
- Keep [`Docs/DeveloperGuide.md`](../Docs/DeveloperGuide.md) (the contributor onboarding guide) current when build, test, or coding-convention changes affect contributors.
142145

143146
#### Documentation Style
144147
- Use clear, technical language
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* ========================================================================
2+
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
3+
*
4+
* OPC Foundation MIT License 1.00
5+
*
6+
* Permission is hereby granted, free of charge, to any person
7+
* obtaining a copy of this software and associated documentation
8+
* files (the "Software"), to deal in the Software without
9+
* restriction, including without limitation the rights to use,
10+
* copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the
12+
* Software is furnished to do so, subject to the following
13+
* conditions:
14+
*
15+
* The above copyright notice and this permission notice shall be
16+
* included in all copies or substantial portions of the Software.
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18+
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19+
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20+
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21+
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22+
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23+
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24+
* OTHER DEALINGS IN THE SOFTWARE.
25+
*
26+
* The complete license agreement can be found here:
27+
* http://opcfoundation.org/License/MIT/1.00/
28+
* ======================================================================*/
29+
30+
namespace Opc.Ua.Lds.Server.Console
31+
{
32+
/// <summary>
33+
/// Centrally managed event id offsets for source-generated log messages in this assembly.
34+
/// </summary>
35+
/// <remarks>
36+
/// Each per-file <c>&lt;ClassName&gt;Log</c> class allocates its event ids relative to the
37+
/// offset constant below, using <c>offset + &lt;zero-based message index&gt;</c>. Every block
38+
/// reserves at least five spare slots for future messages and is rounded up to the next
39+
/// multiple of ten so that ids can be documented and managed from this single location.
40+
/// </remarks>
41+
internal static class ConsoleLdsServerEventIds
42+
{
43+
public const int Program = 0;
44+
}
45+
}

Applications/ConsoleLdsServer/Program.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ await application
181181
}
182182
catch (Exception ex)
183183
{
184-
logger?.LogError(ex, "Fatal error starting LDS.");
184+
logger?.FatalErrorStartingLds(ex);
185185
System.Console.Error.WriteLine(ex);
186186
return 2;
187187
}
@@ -194,4 +194,12 @@ await application
194194
return rootCommand.Parse(args).InvokeAsync();
195195
}
196196
}
197+
198+
internal static partial class ProgramLog
199+
{
200+
[LoggerMessage(EventId = ConsoleLdsServerEventIds.Program + 0, Level = LogLevel.Error,
201+
Message = "Fatal error starting LDS.")]
202+
public static partial void FatalErrorStartingLds(
203+
this Microsoft.Extensions.Logging.ILogger logger, Exception exception);
204+
}
197205
}

Applications/ConsoleReferenceClient/AlarmClientSample.cs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
using Opc.Ua.Client;
3636
using Opc.Ua.Client.Alarms;
3737
using Opc.Ua.Client.Subscriptions.Streaming;
38+
using Quickstarts.ConsoleReferenceClient;
3839

3940
namespace Quickstarts
4041
{
@@ -141,7 +142,7 @@ await alarms.AcknowledgeAsync(
141142
}
142143
catch (Exception ex)
143144
{
144-
m_logger.LogError(ex, "Acknowledge failed");
145+
m_logger.AcknowledgeFailed(ex);
145146
}
146147
}
147148
}
@@ -195,4 +196,12 @@ private static void PrintAlarm(ConditionTypeRecord record)
195196
}
196197
}
197198
}
199+
200+
internal static partial class AlarmClientSampleLog
201+
{
202+
[LoggerMessage(EventId = ConsoleReferenceClientEventIds.AlarmClientSample + 0, Level = LogLevel.Error,
203+
Message = "Acknowledge failed")]
204+
public static partial void AcknowledgeFailed(this ILogger logger, Exception ex);
205+
}
206+
198207
}

0 commit comments

Comments
 (0)