Skip to content

Commit ab5fdb8

Browse files
committed
Optimize TimestampTokenRenderer
1 parent 7356b35 commit ab5fdb8

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/Serilog.Sinks.Console/Sinks/SystemConsole/Output/TimestampTokenRenderer.cs

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// limitations under the License.
1414

1515
using System;
16+
using System.Globalization;
1617
using System.IO;
1718
using Serilog.Events;
1819
using Serilog.Parsing;
@@ -36,9 +37,7 @@ public TimestampTokenRenderer(ConsoleTheme theme, PropertyToken token, IFormatPr
3637

3738
public override void Render(LogEvent logEvent, TextWriter output)
3839
{
39-
// We need access to ScalarValue.Render() to avoid this alloc; just ensures
40-
// that custom format providers are supported properly.
41-
var sv = new ScalarValue(logEvent.Timestamp);
40+
var sv = new DateTimeOffsetValue(logEvent.Timestamp);
4241

4342
var _ = 0;
4443
using (_theme.Apply(output, ConsoleThemeStyle.SecondaryText, ref _))
@@ -56,5 +55,35 @@ public override void Render(LogEvent logEvent, TextWriter output)
5655
}
5756
}
5857
}
58+
59+
readonly struct DateTimeOffsetValue
60+
{
61+
public DateTimeOffsetValue(DateTimeOffset value)
62+
{
63+
Value = value;
64+
}
65+
66+
public DateTimeOffset Value { get; }
67+
68+
public void Render(TextWriter output, string? format = null, IFormatProvider? formatProvider = null)
69+
{
70+
var custom = (ICustomFormatter?)formatProvider?.GetFormat(typeof(ICustomFormatter));
71+
if (custom != null)
72+
{
73+
output.Write(custom.Format(format, Value, formatProvider));
74+
return;
75+
}
76+
77+
#if NET5_0_OR_GREATER
78+
Span<char> buffer = stackalloc char[32];
79+
if (Value.TryFormat(buffer, out int written, format, formatProvider ?? CultureInfo.InvariantCulture))
80+
output.Write(buffer.Slice(0, written));
81+
else
82+
output.Write(Value.ToString(format, formatProvider ?? CultureInfo.InvariantCulture));
83+
#else
84+
output.Write(Value.ToString(format, formatProvider ?? CultureInfo.InvariantCulture));
85+
#endif
86+
}
87+
}
5988
}
6089
}

0 commit comments

Comments
 (0)