且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Core中的Serilog DI,要插入哪个ILogger接口?

更新时间:2023-02-15 23:38:16

选择在应用程序中使用哪个界面确实是一个问题。如果您更喜欢Serilog的 ILogger 较短的方法名称(例如 log.Error log.LogError ),否则,请使用Microsoft的通用 ILogger<> 。您可以控制自己项目中使用的所有依赖项,因此没有充分的技术理由偏爱一个依赖项。

Choosing which interface to use within your application is a matter of taste, really. If you prefer Serilog's ILogger shorter method names (e.g. log.Error vs log.LogError), go with that, otherwise use the Microsoft's generic ILogger<>. You have control over all the dependencies you use in your own projects, so there's no strong technical reason to prefer one over the other.

您可能会对阅读此问题感兴趣在Serilog的回购中:

You might be interested in reading this issue on Serilog's repo:


我应该使用Microsoft.Extensions.Logging.ILogger还是Serilog.ILogger?

I在我所有的项目中都亲自使用Serilog的 ILogger 不仅是因为我更喜欢较短的方法名,还因为我更喜欢 not 在其中插入记录器每个类的每个构造函数,并且使用 Log.ForContext<> 的每个类的上下文记录器,在解决问题时非常有用。例如,

I personally use Serilog's ILogger across all my projects not only because I do prefer the shorter method names, but also because I prefer not to inject a logger in every single constructor of every class, and it's also easy to have a contextual logger for every class using Log.ForContext<>, which is useful when troubleshooting issues. E.g.

public class SomeService
{
    private readonly ILogger _log = Log.ForContext<SomeService>();
    // ...
}

public class SomeRepository
{
    private readonly ILogger _log = Log.ForContext<SomeRepository>();
    // ...
}






但是,如果您正在开发库,我建议您使用Microsoft的通用 ILogger<> ,而不是使用对 Serilog 的依赖,并迫使您的库的使用者也对 Serilog 的依赖。


If you were developing a library though, I'd recommend using Microsoft's generic ILogger<>, of course, instead of taking a dependency on Serilog and force consumers of your library to also take a dependency on Serilog.

Log.Logger 是线程安全的,因此在您进行操作时注册为单例如果您希望所有类共享同一个实例,则上述方法是正确的(没有 SourceContext s )-没错。

Log.Logger is thread-safe, thus registering as a singleton as you are doing above is correct if you want all classes to share the same instance (without SourceContexts) - nothing wrong with that.