Skip to content

Commit

Permalink
MicrosoftConsoleJsonLayout - TimestampLayout replaced by DateLayoutRe…
Browse files Browse the repository at this point in the history
…nderer (#775)
  • Loading branch information
snakefoot authored Nov 24, 2024
1 parent b28d631 commit a8f22ff
Showing 1 changed file with 8 additions and 85 deletions.
93 changes: 8 additions & 85 deletions src/NLog.Extensions.Logging/Layouts/MicrosoftConsoleJsonLayout.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;

namespace NLog.Extensions.Logging
Expand All @@ -17,12 +17,14 @@ public class MicrosoftConsoleJsonLayout : JsonLayout
{
private static readonly string[] EventIdMapper = Enumerable.Range(0, 50).Select(id => id.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray();

private readonly SimpleLayout _timestampLayout = new SimpleLayout("${date:format=o:universalTime=true}");

/// <summary>
/// Initializes a new instance of the <see cref="MicrosoftConsoleJsonLayout" /> class.
/// </summary>
public MicrosoftConsoleJsonLayout()
{
Attributes.Add(new JsonAttribute("Timestamp", new TimestampLayout()));
Attributes.Add(new JsonAttribute("Timestamp", _timestampLayout));
Attributes.Add(new JsonAttribute("EventId", Layout.FromMethod(evt => LookupEventId(evt), LayoutRenderOptions.ThreadAgnostic)) { Encode = false });
Attributes.Add(new JsonAttribute("LogLevel", Layout.FromMethod(evt => ConvertLogLevel(evt.Level), LayoutRenderOptions.ThreadAgnostic)));
Attributes.Add(new JsonAttribute("Category", "${logger}"));
Expand Down Expand Up @@ -77,7 +79,7 @@ public string TimestampFormat
get
{
var index = LookupNamedAttributeIndex("Timestamp");
return index >= 0 ? (Attributes[index].Layout as TimestampLayout)?.TimestampFormat : null;
return index >= 0 ? ((Attributes[index].Layout as SimpleLayout)?.LayoutRenderers?.FirstOrDefault() as DateLayoutRenderer)?.Format : null;
}
set
{
Expand All @@ -89,7 +91,9 @@ public string TimestampFormat

if (!string.IsNullOrEmpty(value))
{
Attributes.Insert(0, new JsonAttribute("Timestamp", new TimestampLayout() { TimestampFormat = value }));
var dateLayoutRenderer = _timestampLayout.LayoutRenderers.First() as DateLayoutRenderer;
dateLayoutRenderer.Format = value;
Attributes.Insert(0, new JsonAttribute("Timestamp", _timestampLayout));
}
}
}
Expand Down Expand Up @@ -152,86 +156,5 @@ private static string ConvertLogLevel(LogLevel logLevel)
else
return nameof(Microsoft.Extensions.Logging.LogLevel.Critical);
}

[ThreadAgnostic]
private sealed class TimestampLayout : Layout
{
public string TimestampFormat
{
get => _timestampFormat;
set
{
if ("o".Equals(value))
value = "O";
_timestampFormat = value;
_timestampFormatString = string.IsNullOrEmpty(value) ? null : $"{{0:{value}}}";
}
}
private string _timestampFormat;
private string _timestampFormatString;

public TimestampLayout()
{
TimestampFormat = "O"; // Round-trip - ISO8601 - yyyy-MM-ddTHH:mm:ss.fffffffZ
}

protected override string GetFormattedMessage(LogEventInfo logEvent)
{
return _timestampFormatString != null ? logEvent.TimeStamp.ToUniversalTime().ToString(TimestampFormat, System.Globalization.CultureInfo.InvariantCulture) : String.Empty;
}

protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target)
{
var utcTimestamp = logEvent.TimeStamp.ToUniversalTime();
if ("O".Equals(TimestampFormat))
{
// yyyy-MM-ddTHH:mm:ss.fffffffZ
Append4DigitsZeroPadded(target, utcTimestamp.Year);
target.Append('-');
Append2DigitsZeroPadded(target, utcTimestamp.Month);
target.Append('-');
Append2DigitsZeroPadded(target, utcTimestamp.Day);
target.Append('T');
Append2DigitsZeroPadded(target, utcTimestamp.Hour);
target.Append(':');
Append2DigitsZeroPadded(target, utcTimestamp.Minute);
target.Append(':');
Append2DigitsZeroPadded(target, utcTimestamp.Second);
target.Append('.');
var ticks = (int)(utcTimestamp.Ticks % 10000000);
Append7DigitsZeroPadded(target, ticks);
target.Append('Z');
}
else if (_timestampFormatString != null)
{
target.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, _timestampFormatString, utcTimestamp);
}
}

internal static void Append2DigitsZeroPadded(StringBuilder builder, int number)
{
builder.Append((char)((number / 10) + '0'));
builder.Append((char)((number % 10) + '0'));
}

internal static void Append4DigitsZeroPadded( StringBuilder builder, int number)
{
builder.Append((char)(((number / 1000) % 10) + '0'));
builder.Append((char)(((number / 100) % 10) + '0'));
builder.Append((char)(((number / 10) % 10) + '0'));
builder.Append((char)((number % 10) + '0'));
}

internal static void Append7DigitsZeroPadded(StringBuilder builder, int number)
{
builder.Append((char)(((number / 1000000) % 10) + '0'));
builder.Append((char)(((number / 100000) % 10) + '0'));
builder.Append((char)(((number / 10000) % 10) + '0'));
builder.Append((char)(((number / 1000) % 10) + '0'));
builder.Append((char)(((number / 100) % 10) + '0'));
builder.Append((char)(((number / 10) % 10) + '0'));
builder.Append((char)((number % 10) + '0'));
}
}
}
}

0 comments on commit a8f22ff

Please sign in to comment.