From e3ceb396687636a570e26cd30fa8da66fe78acf0 Mon Sep 17 00:00:00 2001 From: Pavel Zagrebelin Date: Thu, 5 Oct 2023 23:30:40 +0500 Subject: [PATCH] Increased precision of sended timestamp on .net 7.0 and greater (#209) --- .../Utils/DateTimeOffsetExtensions.cs | 8 ++++++++ .../UtilsTests/DateTimeOffsetExtensionsTests.cs | 13 +++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/Serilog.Sinks.Grafana.Loki/Utils/DateTimeOffsetExtensions.cs b/src/Serilog.Sinks.Grafana.Loki/Utils/DateTimeOffsetExtensions.cs index bc0fe47..0be5c6d 100644 --- a/src/Serilog.Sinks.Grafana.Loki/Utils/DateTimeOffsetExtensions.cs +++ b/src/Serilog.Sinks.Grafana.Loki/Utils/DateTimeOffsetExtensions.cs @@ -12,6 +12,14 @@ namespace Serilog.Sinks.Grafana.Loki.Utils; internal static class DateTimeOffsetExtensions { + #if NET7_0_OR_GREATER + internal static string ToUnixNanosecondsString(this DateTimeOffset offset) => + ((offset.ToUnixTimeMilliseconds() * 1000000) + + (offset.Microsecond * 1000) + + offset.Nanosecond).ToString(); + #else internal static string ToUnixNanosecondsString(this DateTimeOffset offset) => (offset.ToUnixTimeMilliseconds() * 1000000).ToString(); + #endif + } \ No newline at end of file diff --git a/test/Serilog.Sinks.Grafana.Loki.Tests/UtilsTests/DateTimeOffsetExtensionsTests.cs b/test/Serilog.Sinks.Grafana.Loki.Tests/UtilsTests/DateTimeOffsetExtensionsTests.cs index 9fd1db7..e7cd1a8 100644 --- a/test/Serilog.Sinks.Grafana.Loki.Tests/UtilsTests/DateTimeOffsetExtensionsTests.cs +++ b/test/Serilog.Sinks.Grafana.Loki.Tests/UtilsTests/DateTimeOffsetExtensionsTests.cs @@ -25,4 +25,17 @@ public void DateTimeOffsetShouldBeConvertedCorrectly() result.ShouldBe("1621944000000000000"); } + +#if NET7_0_OR_GREATER + [Fact] + public void DateTimeNanosecondsOffsetShouldBeConvertedCorrectly() + { + var dateTimeOffset = + new DateTimeOffset(2021, 05, 25, 12, 00, 00, 777, 888, TimeSpan.Zero).AddMicroseconds(0.999); // There is no other way to set nanoseconds + + var result = dateTimeOffset.ToUnixNanosecondsString(); + + result.ShouldBe("1621944000777888900"); + } +#endif } \ No newline at end of file