Pattern to use Serilog (pass ILogger vs using static Serilog.Log)

跟風遠走 提交于 2019-12-03 01:20:22

There is also a ForContext on Log.Logger, so I would not decide on that basis. If you're doing mocking/testing of logging, you don't want to do that via the global instance - any library code which will do logging in this way should require a ILogger as input, allowing the caller to instrument and/or just pass in Log.Logger as they see fit. If you don't do this, the tests can never run in parallel, which is a big thing to give up.

For me, the main tradeoff is actually whether you're willing to use Enrich.FromLogContext and the LogContext.* interfaces, which hang state off the .NET ExecutionContext, which you need to be careful to not go crazy with. (Yes, arguably you can use a collector sequestered in the ExecutionContext to hack around my previous point, but don't even go there.)

Depending on how your DI is rigged, you may want to take an ILogger<T> in your inputs, but again, unless someone needs to be able to instrument to grab the info, having a static ILogger _logger = Log.ForContext<MyClass>() is fine as long as the Log is wired up early enough.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!