serilog-contrib / SerilogSinksInMemory

In-memory sink for Serilog to use for testing
MIT License
53 stars 7 forks source link

`RenderMessage` does not render same message as serilog does in sinks. #28

Closed rafek1241 closed 2 years ago

rafek1241 commented 2 years ago

issue: RenderMessage does not render same message as serilog does in sinks.

Example test body:

            var data = new Exception("XXX");
            _logger.Information(data, "YYY");

            var logEvent = InMemorySink.Instance.LogEvents.SingleOrDefault();
            logEvent.Should().NotBeNull();
            var message = logEvent!.RenderMessage();

            message
                .Should()
                .Contain("XXX"); //<-- FAILURE. 

Log message in any other sink will look like that:

[09:18:41 INF] YYY
System.Exception: XXX

Within in-memory sink after RenderMessage() called:

YYY
sandermvanvliet commented 2 years ago

This is because the InMemorySink does not specify a default formatter and the output of RenderMessage() is only the text of the log message.

sandermvanvliet commented 2 years ago

See here for example in the DebugSink: https://github.com/serilog/serilog-sinks-debug/blob/b2ef3720f2d743c270eda615700fda8f28d80fdf/src/Serilog.Sinks.Debug/LoggerSinkConfigurationDebugExtensions.cs#L30

The main reason output templates etc are not applied in the InMemorySink is that there is no real output and it therefore doesn't make a lot of sense to capture/apply formatting. That's pretty much in line with the goal of the InMemorySink and that's to capture the LogEvents and not the formatted output of other sinks.

sandermvanvliet commented 2 years ago

If you do want to test the output then you could write a unit test like so:


var inMemorySink = new InMemorySink();
var inMemoryLogger = new LoggerConfiguration().WriteTo.Sink(inMemorySink).CreateLogger();

inMemoryLogger.Information(new Exception("XXX"), "YYY");

var logEvent = inMemorySink.LogEvents.First();

var outputWriter = new StringWriter();
var formatter = new MessageTemplateTextFormatter("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
formatter.Format(logEvent, outputWriter);

outputWriter.ToString().Should().Be(@"[09:18:41 INF] YYY
System.Exception: XXX");