serilog / serilog-sinks-console

Write log events to System.Console as text or JSON, with ANSI theme support
Apache License 2.0
245 stars 72 forks source link

Custom formatter can log on .NET 8 but not on .NET 6 when TraceId is used due to a conflict with System.Diagnostics.DiagnosticSource #160

Open cmhernandezdel opened 3 months ago

cmhernandezdel commented 3 months ago

Using Serilog 3.1.1 but happens to me too with 4.0.0.

When I try to enter into this function in my own formatter:

private void WriteTraceId(LogEvent logEvent, TextWriter output)
{
    if (!logEvent.TraceId.HasValue || !_settings.LogTraceId)
    {
        return;
    }

    output.Write(',');

    output.Write('"');
    output.Write(_settings.TraceIdName);
    output.Write('"');
    output.Write(':');
    _jsonValueFormatter.WriteQuotedJsonString(logEvent.TraceId.Value.ToHexString(), output);
}

I get the following exception:

System.IO.FileNotFoundException: Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. El sistema no puede encontrar el archivo especificado.
File name: 'System.Diagnostics.DiagnosticSource, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
   at Link.VisiotechSerilog.Formatters.SerilogJsonFormatter.WriteTraceId(LogEvent logEvent, TextWriter output)
   at Link.VisiotechSerilog.Formatters.SerilogJsonFormatter.Format(LogEvent logEvent, TextWriter output) in C:\Users\chernandez\Source\visiotechserilog-module\Link.VisiotechSerilog\Link.VisiotechSerilog\Formatters\SerilogJsonFormatter.cs:line 34
   at Serilog.Sinks.SystemConsole.ConsoleSink.Emit(LogEvent logEvent)
   at Serilog.Core.Sinks.SafeAggregateSink.Emit(LogEvent logEvent)

I think the package pulls version 7.0.2 and it's trying to use 7.0.0, this is a netstandard2.1 library which uses Serilog, when we use the library in .NET 8, it works well, but when used in .NET 6 we get this exception.

If I omit TraceId or SpanId logging, it works well, but whenever any of those two properties are involved, I get the exception.

However, the properties are set, as you can see from the debugger:

imagen

If you need more info let me know and I'll try to help!

nblumhardt commented 2 months ago

Hi @cmhernandezdel, thanks for your message.

This is most likely a build issue; I'm not 100% sure how this hangs together around netstandard2.1 but you may be able to sort it out by adding <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="7.0.2" /> (or one of the other versions) directly in your consuming CSPROJ.

FWIW, it may not be possible for you, but retargeting your shared library to .NET 6 (instead of netstandard2.1) will make for a generally nicer tooling experience, as long as you're not running any .NET Core 3.x or 5.x clients.

Hope this helps!