Skip to content

Commit 49df3e6

Browse files
authored
Merge pull request #134 from sungam3r/opt
Optimize TimestampTokenRenderer
2 parents 7356b35 + 212ad03 commit 49df3e6

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

src/Serilog.Sinks.Console/Serilog.Sinks.Console.csproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@
2626
<DefineConstants>$(DefineConstants);RUNTIME_INFORMATION</DefineConstants>
2727
</PropertyGroup>
2828

29+
<PropertyGroup Condition=" '$(TargetFramework)' == 'net5.0' ">
30+
<DefineConstants>$(DefineConstants);FEATURE_SPAN</DefineConstants>
31+
</PropertyGroup>
32+
2933
<ItemGroup>
3034
<PackageReference Include="Serilog" Version="2.10.0" />
3135
<PackageReference Include="Nullable" Version="1.3.0" PrivateAssets="all" />

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 FEATURE_SPAN
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)