Skip to content

Commit e3ceb39

Browse files
authored
Increased precision of sended timestamp on .net 7.0 and greater (#209)
1 parent 593d12c commit e3ceb39

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/Serilog.Sinks.Grafana.Loki/Utils/DateTimeOffsetExtensions.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ namespace Serilog.Sinks.Grafana.Loki.Utils;
1212

1313
internal static class DateTimeOffsetExtensions
1414
{
15+
#if NET7_0_OR_GREATER
16+
internal static string ToUnixNanosecondsString(this DateTimeOffset offset) =>
17+
((offset.ToUnixTimeMilliseconds() * 1000000) +
18+
(offset.Microsecond * 1000) +
19+
offset.Nanosecond).ToString();
20+
#else
1521
internal static string ToUnixNanosecondsString(this DateTimeOffset offset) =>
1622
(offset.ToUnixTimeMilliseconds() * 1000000).ToString();
23+
#endif
24+
1725
}

test/Serilog.Sinks.Grafana.Loki.Tests/UtilsTests/DateTimeOffsetExtensionsTests.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,17 @@ public void DateTimeOffsetShouldBeConvertedCorrectly()
2525

2626
result.ShouldBe("1621944000000000000");
2727
}
28+
29+
#if NET7_0_OR_GREATER
30+
[Fact]
31+
public void DateTimeNanosecondsOffsetShouldBeConvertedCorrectly()
32+
{
33+
var dateTimeOffset =
34+
new DateTimeOffset(2021, 05, 25, 12, 00, 00, 777, 888, TimeSpan.Zero).AddMicroseconds(0.999); // There is no other way to set nanoseconds
35+
36+
var result = dateTimeOffset.ToUnixNanosecondsString();
37+
38+
result.ShouldBe("1621944000777888900");
39+
}
40+
#endif
2841
}

0 commit comments

Comments
 (0)