Skip to content

Commit

Permalink
Use Convert instead of cast for formatting ElapsedMilliseconds (#345)
Browse files Browse the repository at this point in the history
Co-authored-by: ixnas <[email protected]>
Co-authored-by: Martijn Laarman <[email protected]>
  • Loading branch information
3 people authored Apr 4, 2024
1 parent fd459b4 commit 31528cd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/Elastic.CommonSchema.Serilog/LogEventConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -247,11 +247,10 @@ private static Log GetLog(LogEvent e)

private static Event GetEvent(LogEvent e)
{
var elapsedMs = e.TryGetScalarPropertyValue(SpecialKeys.Elapsed, out var elapsed)
? elapsed.Value
: e.TryGetScalarPropertyValue(SpecialKeys.ElapsedMilliseconds, out elapsed)
? elapsed.Value
: null;
var hasElapsedMs = e.TryGetScalarPropertyValue(SpecialKeys.Elapsed, out var elapsedMsObj)
|| e.TryGetScalarPropertyValue(SpecialKeys.ElapsedMilliseconds, out elapsedMsObj);

var elapsedMs = hasElapsedMs ? (double?)Convert.ToDouble(elapsedMsObj!.Value) : null;

var evnt = new Event
{
Expand All @@ -270,7 +269,7 @@ private static Event GetEvent(LogEvent e)
? long.Parse(actionSev)
: (int)e.Level,
Timezone = TimeZoneInfo.Local.StandardName,
Duration = elapsedMs != null ? (long)((double)elapsedMs * 1000000) : null
Duration = elapsedMs != null ? (long)(elapsedMs * 1000000) : null
};

return evnt;
Expand Down
17 changes: 17 additions & 0 deletions tests/Elastic.CommonSchema.Serilog.Tests/MessageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,23 @@ public void SeesMessageWithElapsedProp(string property) => TestLogger((logger, g
info.Metadata.Should().BeNull();
});

[Theory]
[InlineData("Elapsed")]
[InlineData("ElapsedMilliseconds")]
public void SeesMessageWithElapsedLongProp(string property) => TestLogger((logger, getLogEvents) =>
{
logger.Information($"Info {{{property}}}", (long)2);

var logEvents = getLogEvents();
logEvents.Should().HaveCount(1);

var ecsEvents = ToEcsEvents(logEvents);

var (_, info) = ecsEvents.First();
info.Event.Duration.Should().Be(2000000);
info.Metadata.Should().BeNull();
});

[Theory]
[InlineData("Method")]
[InlineData("RequestMethod")]
Expand Down

0 comments on commit 31528cd

Please sign in to comment.