Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/Serilog.Sinks.Console/Serilog.Sinks.Console.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@
<DefineConstants>$(DefineConstants);RUNTIME_INFORMATION</DefineConstants>
</PropertyGroup>

<PropertyGroup Condition=" '$(TargetFramework)' == 'net5.0' ">
<DefineConstants>$(DefineConstants);FEATURE_SPAN</DefineConstants>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Nullable" Version="1.3.0" PrivateAssets="all" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

using System;
using System.Globalization;
using System.IO;
using Serilog.Events;
using Serilog.Parsing;
Expand All @@ -36,9 +37,7 @@ public TimestampTokenRenderer(ConsoleTheme theme, PropertyToken token, IFormatPr

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

var _ = 0;
using (_theme.Apply(output, ConsoleThemeStyle.SecondaryText, ref _))
Expand All @@ -56,5 +55,35 @@ public override void Render(LogEvent logEvent, TextWriter output)
}
}
}

readonly struct DateTimeOffsetValue
{
public DateTimeOffsetValue(DateTimeOffset value)
{
Value = value;
}

public DateTimeOffset Value { get; }

public void Render(TextWriter output, string? format = null, IFormatProvider? formatProvider = null)
{
var custom = (ICustomFormatter?)formatProvider?.GetFormat(typeof(ICustomFormatter));
if (custom != null)
{
output.Write(custom.Format(format, Value, formatProvider));
return;
}

#if FEATURE_SPAN
Span<char> buffer = stackalloc char[32];
if (Value.TryFormat(buffer, out int written, format, formatProvider ?? CultureInfo.InvariantCulture))
output.Write(buffer.Slice(0, written));
else
output.Write(Value.ToString(format, formatProvider ?? CultureInfo.InvariantCulture));
#else
output.Write(Value.ToString(format, formatProvider ?? CultureInfo.InvariantCulture));
#endif
}
}
}
}