使用Microsoft.Extensions.Logging从静态成员登录

编程入门 行业动态 更新时间:2024-10-25 07:19:21
本文介绍了使用Microsoft.Extensions.Logging从静态成员登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

根据 docs.microsoft/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 docs.microsoft/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从静态成员登录

本文发布于:2023-11-15 04:07:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591003.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   成员   Microsoft   Extensions   Logging

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!