Skip to content

Commit

Permalink
NLogProviderOptions with support for CaptureEventId
Browse files Browse the repository at this point in the history
  • Loading branch information
snakefoot committed Oct 16, 2021
1 parent 1d8f06a commit ef67032
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 23 deletions.
32 changes: 32 additions & 0 deletions src/NLog.Extensions.Logging/Logging/EventIdCaptureType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;

namespace NLog.Extensions.Logging
{
/// <summary>
/// Defines EventId capture options
/// </summary>
[Flags]
public enum EventIdCaptureType
{
/// <summary>
/// Skip capture
/// </summary>
None = 0,
/// <summary>
/// Capture entire <see cref="Microsoft.Extensions.Logging.EventId"/> as "EventId"-property (with boxing)
/// </summary>
EventId = 1,
/// <summary>
/// Capture <see cref="Microsoft.Extensions.Logging.EventId.Id"/> as "EventId_Id"-property.
/// </summary>
EventId_Id = 2,
/// <summary>
/// Capture <see cref="Microsoft.Extensions.Logging.EventId.Name"/> as "EventId_Name"-property.
/// </summary>
EventId_Name = 4,
/// <summary>
/// Capture all properties (Legacy)
/// </summary>
All = EventId | EventId_Id | EventId_Name,
}
}
16 changes: 6 additions & 10 deletions src/NLog.Extensions.Logging/Logging/NLogLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ private static object[] CreateLogEventInfoParameters(NLogMessageParameterList me
}

private static readonly object[] SingleItemArray = { null };
private static readonly IList<MessageTemplateParameter> EmptyParameterArray = new MessageTemplateParameter[] { };
private static readonly IList<MessageTemplateParameter> EmptyParameterArray = Array.Empty<MessageTemplateParameter>();

/// <summary>
/// Are all parameters positional and correctly mapped?
Expand Down Expand Up @@ -328,7 +328,7 @@ private static void SetLogEventMessageFormatter(LogEventInfo logEvent, NLogMessa

private void CaptureEventId(LogEventInfo eventInfo, EventId eventId)
{
if (_options.CaptureMessageProperties && (!_options.IgnoreEmptyEventId || eventId.Id != 0 || !String.IsNullOrEmpty(eventId.Name)))
if (_options.CaptureMessageProperties && _options.CaptureEventId != EventIdCaptureType.None && (!_options.IgnoreEmptyEventId || eventId.Id != 0 || !String.IsNullOrEmpty(eventId.Name)))
{
// Attempt to reuse the same string-allocations based on the current <see cref="NLogProviderOptions.EventIdSeparator"/>
var eventIdPropertyNames = _eventIdPropertyNames ?? new Tuple<string, string, string>(null, null, null);
Expand All @@ -341,16 +341,12 @@ private void CaptureEventId(LogEventInfo eventInfo, EventId eventId)

var idIsZero = eventId.Id == 0;
var eventIdObj = idIsZero ? ZeroEventId : GetEventId(eventId.Id);
eventInfo.Properties[eventIdPropertyNames.Item2] = eventIdObj;
if (_options.CaptureEntireEventId)
{
if ((_options.CaptureEventId & EventIdCaptureType.EventId_Id) != 0 && (!idIsZero || !_options.IgnoreEmptyEventId))
eventInfo.Properties[eventIdPropertyNames.Item2] = eventIdObj;
if ((_options.CaptureEventId & EventIdCaptureType.EventId_Name) != 0 && (!string.IsNullOrEmpty(eventId.Name) || !_options.IgnoreEmptyEventId))
eventInfo.Properties[eventIdPropertyNames.Item3] = eventId.Name;
if ((_options.CaptureEventId & EventIdCaptureType.EventId) != 0)
eventInfo.Properties["EventId"] = idIsZero && eventId.Name == null ? EmptyEventId : eventId;
}
else if (!string.IsNullOrEmpty(eventId.Name))
{
eventInfo.Properties[eventIdPropertyNames.Item3] = eventId.Name;
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ internal class NLogMessageParameterList : IList<MessageTemplateParameter>
private static readonly NLogMessageParameterList EmptyList = new NLogMessageParameterList(new KeyValuePair<string, object>[0]);
private static readonly NLogMessageParameterList OriginalMessageList = new NLogMessageParameterList(new[] { new KeyValuePair<string, object>(NLogLogger.OriginalFormatPropertyName, string.Empty) });

public bool HasOriginalMessage => _originalMessageIndex.HasValue;
private readonly int? _originalMessageIndex;

public bool HasComplexParameters => _hasMessageTemplateCapture || _isMixedPositional;
Expand Down Expand Up @@ -60,7 +59,7 @@ public static NLogMessageParameterList TryParse(IReadOnlyList<KeyValuePair<strin

public bool HasMessageTemplateSyntax(bool parseMessageTemplates)
{
return HasOriginalMessage && (HasComplexParameters || (parseMessageTemplates && Count > 0));
return _originalMessageIndex.HasValue && (HasComplexParameters || (parseMessageTemplates && Count > 0));
}

public string GetOriginalMessage(IReadOnlyList<KeyValuePair<string, object>> messageProperties)
Expand Down
18 changes: 9 additions & 9 deletions src/NLog.Extensions.Logging/Logging/NLogProviderOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,18 @@ public class NLogProviderOptions
public string EventIdSeparator { get; set; } = "_";

/// <summary>
/// Skip creating "EventId_Id" and "EventId_Name" as <see cref="LogEventInfo.Properties" /> when <c>default(EventId)</c>
/// Skip capture of "EventId_Id" and "EventId_Name" as <see cref="LogEventInfo.Properties" /> when <c>default(EventId)</c>
/// </summary>
public bool IgnoreEmptyEventId { get; set; } = true;

/// <summary>
/// Control capture of <see cref="Microsoft.Extensions.Logging.EventId"/> as "EventId"-property.
/// </summary>
/// <remarks>
/// Enabling capture of the entire "EventId" will increase memory allocation and gives a performance hit. Faster to use "EventId_Id" + "EventId_Name".
/// </remarks>
public EventIdCaptureType CaptureEventId { get; set; } = EventIdCaptureType.EventId_Id | EventIdCaptureType.EventId_Name;

/// <summary>
/// Enable structured logging by capturing message template parameters with support for "@" and "$". Enables use of ${message:raw=true}
/// </summary>
Expand Down Expand Up @@ -87,14 +95,6 @@ public class NLogProviderOptions
/// <remarks>Will only attempt to load NLog-LoggingConfiguration if valid section-name, and NLog-LoggingConfiguration has not been loaded already.</remarks>
public string LoggingConfigurationSectionName { get; set; } = "NLog";

/// <summary>
/// Enable additional capture of the entire <see cref="Microsoft.Extensions.Logging.EventId"/> as "EventId"-property.
/// </summary>
/// <remarks>
/// Enabling capture of the entire "EventId" will increase memory allocation and gives a performance hit. Faster to use "EventId_Id" + "EventId_Name".
/// </remarks>
public bool CaptureEntireEventId { get; set; }

/// <summary>
/// Enable NLog Targets and Layouts to perform dependency lookup using the Microsoft Dependency Injection IServiceProvider
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void AddNLog_LoggerFactory_LogInfoWithEventId_ShouldLogToNLogWithEventId(
var config = CreateConfigWithMemoryTarget(out var memoryTarget, $"${{event-properties:{eventPropery}}} - ${{message}}");

// Act
loggerFactory.AddNLog(new NLogProviderOptions { EventIdSeparator = "_", CaptureEntireEventId = captureEntireEventId });
loggerFactory.AddNLog(new NLogProviderOptions { EventIdSeparator = "_", CaptureEventId = captureEntireEventId ? EventIdCaptureType.All : EventIdCaptureType.EventId_Id | EventIdCaptureType.EventId_Name });
LogManager.Configuration = config;
var logger = loggerFactory.CreateLogger("logger1");
logger.LogInformation(new EventId(2, "eventId_2"), "test message with {0} arg", 1);
Expand Down Expand Up @@ -108,7 +108,7 @@ public void AddNLog_LoggingBuilder_LogInfoWithEventId_ShouldLogToNLogWithEventId
// Arrange
ILoggingBuilder builder = new LoggingBuilderStub();
var config = CreateConfigWithMemoryTarget(out var memoryTarget, $"${{event-properties:{eventPropery}}} - ${{message}}");
var options = new NLogProviderOptions { EventIdSeparator = "_", CaptureEntireEventId = captureEntireEventId };
var options = new NLogProviderOptions { EventIdSeparator = "_", CaptureEventId = captureEntireEventId ? EventIdCaptureType.All : EventIdCaptureType.EventId_Id | EventIdCaptureType.EventId_Name };

// Act
builder.AddNLog(config, options);
Expand Down

0 comments on commit ef67032

Please sign in to comment.