3

How it works in Serilog

Every ILogger in Serilog has useful method ForContext which essentially creates completely independent child logger with some properties attached.

This is useful for my case, when inside one ASP .NET Core host there are N independent device API's running, each managing some physically connected device. Each API can get it's own ILogger which will for contain property like DeviceName = "Device1", so one can setup appropriate filters in Seq/Greylog/etc.

How it works ASP .NET Core logging API

However, if one uses ILogger from Microsoft.Extensions.Logging, there is no direct counterpart for the ForContext method. The only alternative is BeginScope, which, unfortunately, does not create new isolated logger instance but instead adds values to the global logger scope, from what I understand.

To mitigate this problem, tools like AsyncLocal and SynchronizationContext are used. From what I understand, this works fine for things like correlating HTTP requests because they usually have clear async processing pipeline.

However, in my case each device API runs a chain of somewhat complex Rx .NET observable sequences on task pool scheduler. Even if it is possible to make all of that preserve SynchronizationContext, this will introduce a lot of unneeded complexity.

Question

Is there any way to create independent loggers and/or logger factories, each with their own scope/state? So that, similar to Serilog, anything that uses such logger will have additional properties attached regardless of calling thread or anything else, but these properties will be invisible to any other logger in the application?

Or should I just use Serilog.ILogger instead of Microsoft API, given that this app currently don't use Web API functionality anyway?

ArXen42
  • 139
  • 1
  • 8
  • Same issue here, i thought about injecting `ILoggerFactory`, but that would require me to to set scopes on multiple logger objects if i have global scopes and specific scopes.. – sommmen Jan 13 '22 at 12:18

0 Answers0