使用Microsoft.Extensions.Logging从静态成员登录 [英] Logging from static members with Microsoft.Extensions.Logging

查看:84
本文介绍了使用Microsoft.Extensions.Logging从静态成员登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 https://docs.microsoft.com/zh-我们/aspnet/core/fundamentals/logging ,建议使用 Microsoft.Extensions.Logging 的方法似乎是通过对 ILogger 对象的依赖注入.

在依赖项注入不起作用(或不能很好地起作用)的情况下(例如在扩展方法,类型初始化器,静态属性和其他传递 ILogger 会很麻烦吗?

使用log4net(我的团队之前使用过),常见的模式是:

 公共静态类SomeExtensions{私有静态只读ILog s_log = LogManager.GetLogger(typeof(SomeExtensions));公共静态void ExtensionMethod(此SomeType someType){s_log.Info("...");}} 

是否存在与 Microsoft.Extensions.Logging 相似的建立或推荐模式?

解决方案

感谢@ chris-pratt和@shad 指出 ASP.NET Core记录器方法不能很好地与静态方法配合使用,并且实际上根据文档查找.>

但是,在某些情况下,避免静电是困难的(或在主观上)是不希望的.因此,我的问题的关键是要问在这种情况下是否有建立与 Microsoft.Extensions.Logging 一起使用的模式.

该问题的唯一真正答案是在这篇Stackify文章.其中,它展示了如何设置可从静态上下文中使用的集中式 ILoggerFactory.但是,其结论是仅继续使用NLog或Serilog并将 Microsoft.Extensions.Logging 转发到该库.

According to https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging, the suggested way to use Microsoft.Extensions.Logging seems to be via dependency injection of ILogger objects.

What is the suggested pattern in situations where dependency injection doesn't work (or doesn't work well), such as in extension methods, type initializers, static properties, and other static members where passing an ILogger would be very cumbersome?

With log4net (which my team used before), a common pattern is this:

public static class SomeExtensions
{
  private static readonly ILog s_log = LogManager.GetLogger(typeof(SomeExtensions));

  public static void ExtensionMethod (this SomeType someType)
  {
    s_log.Info("...");
  }
}

Is there a similar established or recommended pattern with Microsoft.Extensions.Logging?

解决方案

Thanks @chris-pratt and @shad for pointing out that the ASP.NET Core loggers approach doesn't play nicely with statics and for actually finding according documentation.

However, there are situations where avoiding statics is difficult or (subjectively) undesirable. So the point of my question was to ask if there was any established pattern for working with the Microsoft.Extensions.Logging in such situations.

The only real answer to that question was in a comment by @alexandre-pires, who pointed me to this Stackify article. Among other things, it shows how to set up a centralized ILoggerFactory that can be used from a static context. However, its conclusion is to just continue using NLog or Serilog and forwarding Microsoft.Extensions.Logging to that library.

这篇关于使用Microsoft.Extensions.Logging从静态成员登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆