加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在ASP.NET Core中分离应用程序级日志记录和框架级日志记录

发布时间:2020-12-15 06:33:51 所属栏目:百科 来源:网络整理
导读:如果我添加日志服务到容器(在ASP.NET 5 RC1中): services.AddSingletonILoggerFactory();services.AddSingleton(typeof(ILogger),typeof(Logger));//or just services.AddLogging(); 然后我可以在我的应用程序图层中使用Logger: class MyAppLogicService{
如果我添加日志服务到容器(在ASP.NET 5 RC1中):
services.AddSingleton<ILoggerFactory>();
services.AddSingleton(typeof(ILogger<>),typeof(Logger<>));
//or just services.AddLogging();

然后我可以在我的应用程序图层中使用Logger:

class MyAppLogicService
{
    public MyAppLogicService(ILogger<MyAppLogicService> logger) 
    { 
        logger.LogInformation("Hey");
    }
}

但在这种情况下,我的logger.LogInformation()事件将与不重要的框架信息事件混合(根据最多10个请求的开发人员).

ASP.NET 5 documentation states:

It is recommended that you perform application logging at the level of
your application and its APIs,not at the level of the framework. The
framework already has logging built in which can be enabled simply by
setting the appropriate logging verbosity level.

这是什么意思?这是否意味着不推荐在客户端代码(应用程序逻辑)中使用ILogger / ILoggerFactory?

从框架级日志记录中分离应用级别日志记录的优雅解决方案是什么?
现在我使用的是Serilog并通过ContextSource进行过滤,但是这远远不够优雅

解决方法

perform application logging at the level of your application and its APIs,not at the level of the framework
I think the message here is that you should not try and log every request details,because that is already logged by the framework.

至于混合框架日志事件和应用程序日志事件 – 文档还说明:

When a logger is created,a category name must be provided. The category name specifies the source of the logging events. By convention this string is hierarchical,with categories separated by dot (.) characters. Some logging providers have filtering support that leverages this convention,making it easier to locate logging output of interest.

默认情况下,当使用注入ILogger< MyAppLogicService>时,如果类的全名(具有命名空间),则为类名.

因此,为了避免使用框架信息来混淆您的日志,您可以通过仅包含与您的命名空间相匹配的类别来过滤出所有噪点.当使用ConsoleLogger时,它将如下所示:

loggerFactory.AddConsole((cat,level) => cat.StartsWith("mynamespace."));

我想这类似于“使用Serilog并通过ContextSource进行过滤”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读