Skip to content

Commit

Permalink
ShortDateLayoutRenderer with support for IRawValue + IStringValueRend…
Browse files Browse the repository at this point in the history
…erer
  • Loading branch information
snakefoot committed Apr 27, 2019
1 parent 21a614c commit 3e95b3f
Showing 1 changed file with 30 additions and 9 deletions.
39 changes: 30 additions & 9 deletions src/NLog/LayoutRenderers/ShortDateLayoutRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,15 @@ namespace NLog.LayoutRenderers
using System.Globalization;
using System.Text;
using NLog.Config;
using NLog.Internal;

/// <summary>
/// The short date in a sortable format yyyy-MM-dd.
/// </summary>
[LayoutRenderer("shortdate")]
[ThreadAgnostic]
[ThreadSafe]
public class ShortDateLayoutRenderer : LayoutRenderer
public class ShortDateLayoutRenderer : LayoutRenderer, IRawValue, IStringValueRenderer
{
/// <summary>
/// Gets or sets a value indicating whether to output UTC time instead of local time.
Expand All @@ -63,22 +64,42 @@ public class ShortDateLayoutRenderer : LayoutRenderer
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
var timestamp = logEvent.TimeStamp;
if (UniversalTime)
string formattedDate = GetStringValue(logEvent);
builder.Append(formattedDate);
}

private string GetStringValue(LogEventInfo logEvent)
{
DateTime currentDate = GetValue(logEvent);

var cachedDateFormatted = _cachedDateFormatted;
if (cachedDateFormatted.Date != currentDate)
{
timestamp = timestamp.ToUniversalTime();
var formatTime = currentDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
_cachedDateFormatted = cachedDateFormatted = new CachedDateFormatted(currentDate, formatTime);
}

var cachedDateFormatted = _cachedDateFormatted;
if (cachedDateFormatted.Date != timestamp.Date)
return cachedDateFormatted.FormattedDate;
}

private DateTime GetValue(LogEventInfo logEvent)
{
var timestamp = logEvent.TimeStamp;
if (UniversalTime)
{
var formatTime = timestamp.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
_cachedDateFormatted = cachedDateFormatted = new CachedDateFormatted(timestamp.Date, formatTime);
timestamp = timestamp.ToUniversalTime();
}
return timestamp.Date;
}

builder.Append(cachedDateFormatted.FormattedDate);
bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value)
{
value = GetValue(logEvent);
return true;
}

string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) => GetStringValue(logEvent);

private class CachedDateFormatted
{
public CachedDateFormatted(DateTime date, string formattedDate)
Expand Down

0 comments on commit 3e95b3f

Please sign in to comment.