Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
12b3643
Add NLog instrumentation for OpenTelemetry .NET Auto-Instrumentation
danifitz Aug 6, 2025
dd0eee6
Fix: https://github.com/open-telemetry/opentelemetry-dotnet-instrumen…
danifitz Aug 11, 2025
1b5ee77
Fix https://github.com/open-telemetry/opentelemetry-dotnet-instrument…
danifitz Aug 11, 2025
489fa3b
Fix: https://github.com/open-telemetry/opentelemetry-dotnet-instrumen…
danifitz Aug 11, 2025
638a6aa
Test: https://github.com/open-telemetry/opentelemetry-dotnet-instrume…
danifitz Aug 11, 2025
206be87
feat: refactor NLog instrumentation to use standard NLog Target archi…
danifitz Aug 20, 2025
799ef71
refactor: remove unused NLog.Extensions.Logging from TestApplication.…
danifitz Aug 20, 2025
4401757
refactor: optimize NLog target for async compatibility and performance
danifitz Aug 21, 2025
0fcf644
feat: add hybrid typed layout support for NLog version compatibility
danifitz Aug 27, 2025
4ffa40a
feat: implement NLog v5.3.4+ typed layouts for OpenTelemetryTarget
danifitz Sep 10, 2025
f6cd7d5
fix test coverage
danifitz Sep 10, 2025
665fb09
fix: correct NLog bridge EmitLog method call to match OpenTelemetry SDK
danifitz Sep 10, 2025
3a79c85
refactor: simplify NLog target configuration to use environment varia…
danifitz Sep 11, 2025
f6957e6
Removed NLog from AssemblyInfo
danifitz Sep 24, 2025
b078f85
feat: add NLog instrumentation with duck typing and NLog 6.x support
danifitz Sep 24, 2025
4a0d5a3
Merge branch 'main' into feature/nlog-instrumentation
danifitz Sep 24, 2025
bf571f5
fix CHANGELOG
Kielek Sep 30, 2025
16b004e
Fix build errors
Kielek Sep 30, 2025
e650142
commit generated file
Kielek Sep 30, 2025
c41f73c
Merge branch 'main' into feature/nlog-instrumentation
Kielek Sep 30, 2025
e66da6a
Move NLog version to test folder
Kielek Sep 30, 2025
3d5aff8
cleanup solution
Kielek Sep 30, 2025
ad1c62f
add NLOG to dictionary
Kielek Sep 30, 2025
54dd6da
typo fixes
Kielek Sep 30, 2025
0602818
remove reference to NLog.Extensions.Logging
Kielek Sep 30, 2025
903ab69
Update tested versions
Kielek Sep 30, 2025
4702a68
Minimal assembly version set to 4.0.0
Kielek Sep 30, 2025
951c355
fix sln file
Kielek Sep 30, 2025
29d4251
remove reference to System.Private.Uri
Kielek Sep 30, 2025
29bde76
Fix compilation for tests app
Kielek Sep 30, 2025
911fbd8
Apply suggestions from code review
lachmatt Oct 1, 2025
60311e1
Merge branch 'main' into feature/nlog-instrumentation
Kielek Oct 1, 2025
d912c7e
Merge branch 'main' into feature/nlog-instrumentation
Kielek Oct 1, 2025
c6b7bde
Merge branch 'main' into feature/nlog-instrumentation
Kielek Oct 2, 2025
fad8ea4
Fix issue occurring in VS
Kielek Oct 2, 2025
e3d9274
Add missing settings test case
Kielek Oct 2, 2025
e95e972
remove redundant lines
Kielek Oct 2, 2025
62f933d
Sync implementation with available documentation
Kielek Oct 2, 2025
33546ee
user facing documentation
Kielek Oct 2, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .cspell/other.txt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ mycompanymyproductmylibrary
MYSQLCONNECTOR
MYSQLDATA
NETRUNTIME
NLOG
Npgsql
NSERVICEBUS
omnisharp
Expand All @@ -58,9 +59,9 @@ protos
RABBITMQ
Serilog
spdlog
srcs
SQLCLIENT
sqlserver
srcs
STACKEXCHANGEREDIS
TMPDIR
tracesexporter
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ This component adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.h

### Added

- Support for [`NLog`](https://www.nuget.org/packages/NLog/)
logs instrumentation for versions `5.*` and `6.*` on .NET using duck typing
for zero-config auto-injection.

### Changed

#### Dependency updates
Expand Down
19 changes: 19 additions & 0 deletions OpenTelemetry.AutoInstrumentation.sln
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SdkVersionAnalyzer", "tools
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApplication.Log4NetBridge", "test\test-applications\integrations\TestApplication.Log4NetBridge\TestApplication.Log4NetBridge.csproj", "{926B7C03-42C2-4192-94A7-CD0B1C693279}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApplication.NLogBridge", "test\test-applications\integrations\TestApplication.NLogBridge\TestApplication.NLogBridge.csproj", "{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApplication.SelectiveSampler", "test\test-applications\integrations\TestApplication.SelectiveSampler\TestApplication.SelectiveSampler.csproj", "{FD1A1ABD-6A48-4E94-B5F7-2081AFCD1BBB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApplication.ProfilerSpanStoppageHandling", "test\test-applications\integrations\TestApplication.ProfilerSpanStoppageHandling\TestApplication.ProfilerSpanStoppageHandling.csproj", "{665280EB-F428-4C04-A293-33228C73BF8A}"
Expand Down Expand Up @@ -1535,6 +1537,22 @@ Global
{926B7C03-42C2-4192-94A7-CD0B1C693279}.Release|x64.Build.0 = Release|x64
{926B7C03-42C2-4192-94A7-CD0B1C693279}.Release|x86.ActiveCfg = Release|x86
{926B7C03-42C2-4192-94A7-CD0B1C693279}.Release|x86.Build.0 = Release|x86
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Debug|Any CPU.ActiveCfg = Debug|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Debug|Any CPU.Build.0 = Debug|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Debug|ARM64.ActiveCfg = Debug|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Debug|ARM64.Build.0 = Debug|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Debug|x64.ActiveCfg = Debug|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Debug|x64.Build.0 = Debug|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Debug|x86.ActiveCfg = Debug|x86
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Debug|x86.Build.0 = Debug|x86
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Release|Any CPU.ActiveCfg = Release|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Release|Any CPU.Build.0 = Release|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Release|ARM64.ActiveCfg = Release|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Release|ARM64.Build.0 = Release|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Release|x64.ActiveCfg = Release|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Release|x64.Build.0 = Release|x64
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Release|x86.ActiveCfg = Release|x86
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D}.Release|x86.Build.0 = Release|x86
{FD1A1ABD-6A48-4E94-B5F7-2081AFCD1BBB}.Debug|Any CPU.ActiveCfg = Debug|x64
{FD1A1ABD-6A48-4E94-B5F7-2081AFCD1BBB}.Debug|Any CPU.Build.0 = Debug|x64
{FD1A1ABD-6A48-4E94-B5F7-2081AFCD1BBB}.Debug|ARM64.ActiveCfg = Debug|x64
Expand Down Expand Up @@ -1657,6 +1675,7 @@ Global
{AA3E0C5C-A4E2-46AB-BD18-2D30D3ABF692} = {E409ADD3-9574-465C-AB09-4324D205CC7C}
{C75FA076-D460-414B-97F7-6F8D0E85AE74} = {00F4C92D-6652-4BD8-A334-B35D3E711BE6}
{926B7C03-42C2-4192-94A7-CD0B1C693279} = {E409ADD3-9574-465C-AB09-4324D205CC7C}
{A7B8C9D0-1E2F-3A4B-5C6D-7E8F9A0B1C2D} = {E409ADD3-9574-465C-AB09-4324D205CC7C}
{FD1A1ABD-6A48-4E94-B5F7-2081AFCD1BBB} = {E409ADD3-9574-465C-AB09-4324D205CC7C}
{665280EB-F428-4C04-A293-33228C73BF8A} = {E409ADD3-9574-465C-AB09-4324D205CC7C}
EndGlobalSection
Expand Down
9 changes: 9 additions & 0 deletions build/LibraryVersions.g.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,15 @@ public static partial class LibraryVersion
new("3.2.0"),
]
},
{
"TestApplication.NLogBridge",
[
new("5.0.0"),
new("5.3.4"),
new("6.0.0"),
new("6.0.4"),
]
},
{
"TestApplication.MassTransit",
[
Expand Down
4 changes: 4 additions & 0 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ due to lack of stable semantic convention.
|-----------|---------------------------------------------------------------------------------------------------------------------------------|--------------------|------------------------|-----------------------------------------------------------------------------------------------------------------------------------|
| `ILOGGER` | [Microsoft.Extensions.Logging](https://www.nuget.org/packages/Microsoft.Extensions.Logging) **Not supported on .NET Framework** | ≥9.0.0 | bytecode or source \[1\] | [Experimental](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/versioning-and-stability.md) |
| `LOG4NET` | [log4net](https://www.nuget.org/packages/log4net) \[2\] | ≥2.0.13 && < 4.0.0 | bytecode | [Experimental](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/versioning-and-stability.md) |
| `NLOG` | [NLog](https://www.nuget.org/packages/NLog) \[3\] | ≥5.0.0 && < 7.0.0 | bytecode | [Experimental](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/versioning-and-stability.md) |

\[1\]: For ASP.NET Core applications, the `LoggingBuilder` instrumentation
can be enabled without using the .NET CLR Profiler by setting
Expand All @@ -216,6 +217,9 @@ the `ASPNETCORE_HOSTINGSTARTUPASSEMBLIES` environment variable to
\[2\]: Instrumentation provides both [trace context injection](./log-trace-correlation.md#log4net-trace-context-injection)
and [logs bridge](./log4net-bridge.md).

\[3\]: Instrumentation provides both [trace context injection](./log-trace-correlation.md#log4net-trace-context-injection)
and [logs bridge](./nlog-bridge.md).

### Instrumentation options

| Environment variable | Description | Default value | Status |
Expand Down
23 changes: 23 additions & 0 deletions docs/log-trace-correlation.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,26 @@ Following properties are set by default on the collection of logging event's pro

This allows for trace context to be logged into currently configured log destination,
e.g. a file. In order to use them, pattern needs to be updated.

### `NLog`

See [`nlog-bridge`](./nlog-bridge.md).

## `NLog` trace context injection

> [!IMPORTANT]
> NLog trace context injection is an experimental feature.

The `NLog` trace context injection is enabled by default.
It can be disabled by setting `OTEL_DOTNET_AUTO_LOGS_NLOG_INSTRUMENTATION_ENABLED` to `false`.

Context injection is supported for `NLOG` in versions >= 5.0.0 && < 7.0.0

Following properties are set by default on the collection of logging event's properties:

- `trace_id`
- `span_id`
- `trace_flags`

This allows for trace context to be logged into currently configured log destination,
e.g. a file. In order to use them, pattern needs to be updated.
2 changes: 0 additions & 2 deletions docs/log4net-bridge.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,3 @@ In order for the bridge to be added, at least 1 other appender has to be configu
Bridge should not be used when appenders are configured for both root and component loggers.
Enabling a bridge in such scenario would result in bridge being appended to both appender collections,
and logs duplication.


46 changes: 46 additions & 0 deletions docs/nlog-bridge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# `NLog` [logs bridge](https://opentelemetry.io/docs/specs/otel/glossary/#log-appender--bridge)

> [!IMPORTANT]
> NLog bridge is an experimental feature.

The `NLog` logs bridge is disabled by default. In order to enable it,
set `OTEL_DOTNET_AUTO_LOGS_ENABLE_NLOG_BRIDGE` to `true`.

Bridge is supported for `NLOG` in versions >= 5.0.0 && < 7.0.0

If `NLOG` is used as a [logging provider](https://learn.microsoft.com/en-us/dotnet/core/extensions/logging-providers),
`NLOG` bridge should not be enabled, in order to reduce possibility of
duplicated logs export.

## `NLog` logging events conversion

`NLog`'s `ILoggingEvent`s are converted to OpenTelemetry log records in
a following way:

- `TimeStamp` is set as a `Timestamp`
- `Level.Name` is set as a `SeverityText`
- `FormattedMessage` is set as a `Body` if it is available
- Otherwise, `Message` is set as a `Body`
- `LoggerName` is set as an `InstrumentationScope.Name`
- `GetProperties()`, apart from builtin properties prefixed with `nlog:`, `NLog.`,
are added as attributes
- `Exception` is used to populate the following properties: `exception.type`,
`exception.message`, `exception.stacktrace`
- `Level.Value` is mapped to `SeverityNumber` as outlined in the next section

### `NLog` level severity mapping

`NLog` levels are mapped to OpenTelemetry severity types according to
following rules based on their numerical values.

Levels with numerical values of:

- Equal to `LogLevel.Fatal` is mapped to `LogRecordSeverity.Fatal`
- Equal to `LogLevel.Error` is mapped to `LogRecordSeverity.Error`
- Equal to `LogLevel.Warn` is mapped to `LogRecordSeverity.Warn`
- Equal to `LogLevel.Info` is mapped to `LogRecordSeverity.Info`
- Equal to `LogLevel.Debug` is mapped to `LogRecordSeverity.Debug`
- Equal to `LogLevel.Trace` is mapped to `LogRecordSeverity.Trace`
- Equal to `LogLevel.Off` is mapped to `LogRecordSeverity.Trace`
- Any other is mapped to `LogRecordSeverity.Info`.

Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
OpenTelemetry.AutoInstrumentation.Instrumentations.NLog.Bridge.Integrations.LoggerIntegration
OpenTelemetry.AutoInstrumentation.Instrumentations.RabbitMqLegacy.Integrations.AsyncDefaultBasicConsumerIntegration
OpenTelemetry.AutoInstrumentation.Instrumentations.RabbitMqLegacy.Integrations.DefaultBasicConsumerIntegration
OpenTelemetry.AutoInstrumentation.Instrumentations.RabbitMqLegacy.Integrations.ModelBaseBasicGetIntegration
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
OpenTelemetry.AutoInstrumentation.Instrumentations.NLog.Bridge.Integrations.LoggerIntegration
OpenTelemetry.AutoInstrumentation.Instrumentations.RabbitMqLegacy.Integrations.AsyncDefaultBasicConsumerIntegration
OpenTelemetry.AutoInstrumentation.Instrumentations.RabbitMqLegacy.Integrations.DefaultBasicConsumerIntegration
OpenTelemetry.AutoInstrumentation.Instrumentations.RabbitMqLegacy.Integrations.ModelBaseBasicGetIntegration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,12 @@ public static class Logs
/// </summary>
public const string EnableLog4NetBridge = "OTEL_DOTNET_AUTO_LOGS_ENABLE_LOG4NET_BRIDGE";

/// <summary>
/// Configuration key for whether or not experimental NLog bridge
/// should be enabled.
/// </summary>
public const string EnableNLogBridge = "OTEL_DOTNET_AUTO_LOGS_ENABLE_NLOG_BRIDGE";

/// <summary>
/// Configuration key for disabling all log instrumentations.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,9 @@ internal enum LogInstrumentation
/// Log4Net instrumentation.
/// </summary>
Log4Net = 1,

/// <summary>
/// NLog instrumentation.
/// </summary>
NLog = 2,
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ internal class LogSettings : Settings
/// </summary>
public bool EnableLog4NetBridge { get; private set; }

/// <summary>
/// Gets a value indicating whether the experimental NLog bridge is enabled.
/// </summary>
public bool EnableNLogBridge { get; private set; }

/// <summary>
/// Gets the list of enabled instrumentations.
/// </summary>
Expand All @@ -54,6 +59,7 @@ protected override void OnLoadEnvVar(Configuration configuration)

IncludeFormattedMessage = configuration.GetBool(ConfigurationKeys.Logs.IncludeFormattedMessage) ?? false;
EnableLog4NetBridge = configuration.GetBool(ConfigurationKeys.Logs.EnableLog4NetBridge) ?? false;
EnableNLogBridge = configuration.GetBool(ConfigurationKeys.Logs.EnableNLogBridge) ?? false;

var instrumentationEnabledByDefault =
configuration.GetBool(ConfigurationKeys.Logs.LogsInstrumentationEnabled) ??
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal static partial class InstrumentationDefinitions
{
private static NativeCallTargetDefinition[] GetDefinitionsArray()
{
var nativeCallTargetDefinitions = new List<NativeCallTargetDefinition>(36);
var nativeCallTargetDefinitions = new List<NativeCallTargetDefinition>(37);
// Traces
var tracerSettings = Instrumentation.TracerSettings.Value;
if (tracerSettings.TracesEnabled)
Expand Down Expand Up @@ -101,6 +101,12 @@ private static NativeCallTargetDefinition[] GetDefinitionsArray()
nativeCallTargetDefinitions.Add(new("log4net", "log4net.Appender.AppenderCollection", "ToArray", ["log4net.Appender.IAppender[]"], 2, 0, 13, 3, 65535, 65535, AssemblyFullName, "OpenTelemetry.AutoInstrumentation.Instrumentations.Log4Net.Bridge.Integrations.AppenderCollectionIntegration"));
nativeCallTargetDefinitions.Add(new("log4net", "log4net.Util.AppenderAttachedImpl", "AppendLoopOnAppenders", ["System.Int32", "log4net.Core.LoggingEvent"], 2, 0, 13, 3, 65535, 65535, AssemblyFullName, "OpenTelemetry.AutoInstrumentation.Instrumentations.Log4Net.TraceContextInjection.Integrations.AppenderAttachedImplIntegration"));
}

// NLog
if (logSettings.EnabledInstrumentations.Contains(LogInstrumentation.NLog))
{
nativeCallTargetDefinitions.Add(new("NLog", "NLog.Logger", "Log", ["System.Void", "NLog.LogEventInfo"], 5, 0, 0, 6, 65535, 65535, AssemblyFullName, "OpenTelemetry.AutoInstrumentation.Instrumentations.NLog.Bridge.Integrations.LoggerIntegration"));
}
}

// Metrics
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal static partial class InstrumentationDefinitions
{
private static NativeCallTargetDefinition[] GetDefinitionsArray()
{
var nativeCallTargetDefinitions = new List<NativeCallTargetDefinition>(39);
var nativeCallTargetDefinitions = new List<NativeCallTargetDefinition>(40);
// Traces
var tracerSettings = Instrumentation.TracerSettings.Value;
if (tracerSettings.TracesEnabled)
Expand Down Expand Up @@ -104,6 +104,12 @@ private static NativeCallTargetDefinition[] GetDefinitionsArray()
{
nativeCallTargetDefinitions.Add(new("Microsoft.Extensions.Logging", "Microsoft.Extensions.Logging.LoggingBuilder", ".ctor", ["System.Void", "Microsoft.Extensions.DependencyInjection.IServiceCollection"], 9, 0, 0, 9, 65535, 65535, AssemblyFullName, "OpenTelemetry.AutoInstrumentation.Instrumentations.Logger.LoggingBuilderIntegration"));
}

// NLog
if (logSettings.EnabledInstrumentations.Contains(LogInstrumentation.NLog))
{
nativeCallTargetDefinitions.Add(new("NLog", "NLog.Logger", "Log", ["System.Void", "NLog.LogEventInfo"], 5, 0, 0, 6, 65535, 65535, AssemblyFullName, "OpenTelemetry.AutoInstrumentation.Instrumentations.NLog.Bridge.Integrations.LoggerIntegration"));
}
}

// Metrics
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

using System.Reflection;
using OpenTelemetry.AutoInstrumentation.DuckTyping;
using OpenTelemetry.AutoInstrumentation.Logging;

namespace OpenTelemetry.AutoInstrumentation.Instrumentations.NLog.AutoInjection;

internal static class NLogAutoInjector
{
private static readonly IOtelLogger Logger = OtelLogging.GetLogger();
private static int _attempted;

public static void EnsureConfigured()
{
if (Interlocked.Exchange(ref _attempted, 1) != 0)
{
return;
}

try
{
var nlogLogManager = Type.GetType("NLog.LogManager, NLog");
if (nlogLogManager is null)
{
return;
}

var configurationProperty = nlogLogManager.GetProperty("Configuration", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (configurationProperty is null)
{
return;
}

var configuration = configurationProperty.GetValue(null);
if (configuration is null)
{
var configurationType = Type.GetType("NLog.Config.LoggingConfiguration, NLog");
configuration = Activator.CreateInstance(configurationType!);
configurationProperty.SetValue(null, configuration);
}

// Create the OpenTelemetry target instance and wrap it in a duck proxy
var otelTarget = new OpenTelemetryTarget();
var targetType = Type.GetType("NLog.Targets.TargetWithContext, NLog", false);
if (targetType is null)
{
Logger.Warning("NLog auto-injection skipped: TargetWithContext type not found.");
return;
}

var targetProxy = otelTarget.DuckImplement(targetType);

// Add target to configuration
var addTargetMethod = configuration!.GetType().GetMethod("AddTarget", BindingFlags.Instance | BindingFlags.Public);
addTargetMethod?.Invoke(configuration, new object?[] { "otlp", targetProxy });

// Create rule: * -> otlp (minlevel: Trace)
var loggingRuleType = Type.GetType("NLog.Config.LoggingRule, NLog");
var logLevelType = Type.GetType("NLog.LogLevel, NLog");
var traceLevel = logLevelType?.GetProperty("Trace", BindingFlags.Static | BindingFlags.Public)?.GetValue(null);
var rule = Activator.CreateInstance(loggingRuleType!, new object?[] { "*", traceLevel, targetProxy });

var loggingRulesProp = configuration.GetType().GetProperty("LoggingRules", BindingFlags.Instance | BindingFlags.Public);
var rulesList = loggingRulesProp?.GetValue(configuration) as System.Collections.IList;
rulesList?.Add(rule);

// Apply configuration
var reconfigMethod = nlogLogManager.GetMethod("ReconfigExistingLoggers", BindingFlags.Static | BindingFlags.Public);
reconfigMethod?.Invoke(null, null);

Logger.Information("NLog OpenTelemetryTarget auto-injected.");
}
catch (Exception ex)
{
Logger.Warning(ex, "NLog OpenTelemetryTarget auto-injection failed.");
}
}
}
Loading
Loading