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

标签 c# logging 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.

默认情况下,当使用注入(inject)时 ILogger<MyAppLogicService> , 类别名称如果是类的全名(带命名空间)。

因此,为了避免框架信息使您的日志困惑,您可以通过仅包括与您的命名空间匹配的类别来过滤掉所有噪音。使用 ConsoleLogger 时它看起来像这样:

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

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

关于c# - 在 ASP.NET Core 中分离应用程序级日志记录和框架级日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35039070/

相关文章:

c# - 使用 c# 和 TLSv1.2 连接到 LDAP

c# - Prism RequestNavigate 在启动时立即从 PrismApplication 导航

java - 如何在java中使用日志级别

java - 流式传输远程日志文件的有效方法

asp.net-core - 如何获取 ASP.NET Core 应用程序名称?

c# - 如何访问服务器上的Jquery TreeView?

c# - 使用 JQuery 和 Cookie 插件创建一个非 url 编码值的 cookie

logging - 在asp.net core web api中获取真实的总请求时间

asp.net-core - DependencyContext.Default 在.net core测试项目中抛出错误

asp.net-core - 如何获取所有版本的KRE?