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

前端之家收集整理的这篇文章主要介绍了c# – 在ASP.NET Core中分离应用程序级日志记录和框架级日志记录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我添加日志服务到容器(在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进行过滤”.

原文链接:https://www.f2er.com/netcore/95251.html

猜你在找的.NET Core相关文章