ASP.NET Core 中的日志记录Logging in ASP.NET Core

作者:Steve SmithTom DykstraBy Steve Smith and Tom Dykstra

ASP.NET Core 支持适用于各种内置和第三方日志记录提供程序的日志记录 API。ASP.NET Core supports a logging API that works with a variety of built-in and third-party logging providers. 本文介绍了如何将日志记录 API 与内置提供程序一起使用。This article shows how to use the logging API with built-in providers.

查看或下载示例代码如何下载View or download sample code (how to download)

添加提供程序Add providers

日志记录提供程序会显示或存储日志。A logging provider displays or stores logs. 例如,控制台提供程序在控制台上显示日志,Azure Application Insights 提供程序会将这些日志存储在 Azure Application Insights 中。For example, the Console provider displays logs on the console, and the Azure Application Insights provider stores them in Azure Application Insights. 可通过添加多个提供程序将日志发送到多个目标。Logs can be sent to multiple destinations by adding multiple providers.

要添加提供程序,请在 Program.cs 中调用提供程序的 Add{provider name} 扩展方法 :To add a provider, call the provider's Add{provider name} extension method in Program.cs:

public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 
                      optional: true, reloadOnChange: true);
            config.AddEnvironmentVariables();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            // Requires `using Microsoft.Extensions.Logging;`
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

前面的代码需要引用 Microsoft.Extensions.LoggingMicrosoft.Extensions.ConfigurationThe preceding code requires references to Microsoft.Extensions.Logging and Microsoft.Extensions.Configuration.

默认项目模板调用 CreateDefaultBuilder,该操作将添加以下日志记录提供程序:The default project template calls CreateDefaultBuilder, which adds the following logging providers:

  • 控制台Console
  • 调试Debug
  • EventSource(启动位置:ASP.NET Core 2.2)EventSource (starting in ASP.NET Core 2.2)
public static void Main(string[] args)
{
    CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

如果使用 CreateDefaultBuilder,则可自行选择提供程序来替换默认提供程序。If you use CreateDefaultBuilder, you can replace the default providers with your own choices. 调用 ClearProviders,然后添加所需的提供程序。Call ClearProviders, and add the providers you want.

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();

    var todoRepository = host.Services.GetRequiredService<ITodoRepository>();
    todoRepository.Add(new Core.Model.TodoItem() { Name = "Feed the dog" });
    todoRepository.Add(new Core.Model.TodoItem() { Name = "Walk the dog" });

    var logger = host.Services.GetRequiredService<ILogger<Program>>();
    logger.LogInformation("Seeded the database.");

    host.Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();
        });

要使用提供程序,请安装其 NuGet 包,并在 ILoggerFactory 的实例上调用提供程序的扩展方法:To use a provider, install its NuGet package and call the provider's extension method on an instance of ILoggerFactory:

public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory
        .AddConsole()
        .AddDebug();

ASP.NET Core 依赖关系注入 (DI) 将提供 ILoggerFactory 实例。ASP.NET Core dependency injection (DI) provides the ILoggerFactory instance. Microsoft.Extensions.Logging.ConsoleMicrosoft.Extensions.Logging.Debug 包中定义了 AddConsoleAddDebug 扩展方法。The AddConsole and AddDebug extension methods are defined in the Microsoft.Extensions.Logging.Console and Microsoft.Extensions.Logging.Debug packages. 每个扩展方法都调用 ILoggerFactory.AddProvider 方法,传入提供程序的一个实例。Each extension method calls the ILoggerFactory.AddProvider method, passing in an instance of the provider.

备注

示例应用Startup.Configure 方法中添加了日志提供程序。The sample app adds logging providers in the Startup.Configure method. 要从先前执行的代码获取日志输出,请在 Startup 类构造函数中添加日志提供程序。To obtain log output from code that executes earlier, add logging providers in the Startup class constructor.

详细了解内置日志记录提供程序,以及本文稍后部分介绍的第三方日志记录提供程序Learn more about built-in logging providers and third-party logging providers later in the article.

创建日志Create logs

从 DI 中获取 ILogger<TCategoryName> 对象。Get an ILogger<TCategoryName> object from DI.

以下控制器示例会创建 InformationWarning 日志。The following controller example creates Information and Warning logs. 类别为 TodoApiSample.Controllers.TodoController(示例应用中 TodoController 的完全限定类名) :The category is TodoApiSample.Controllers.TodoController (the fully qualified class name of TodoController in the sample app):

public class TodoController : Controller
{
    private readonly ITodoRepository _todoRepository;
    private readonly ILogger _logger;

    public TodoController(ITodoRepository todoRepository,
        ILogger<TodoController> logger)
    {
        _todoRepository = todoRepository;
        _logger = logger;
    }
public IActionResult GetById(string id)
{
    _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
    var item = _todoRepository.Find(id);
    if (item == null)
    {
        _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
        return NotFound();
    }
    return new ObjectResult(item);
}

以下 Razor 页面示例会创建“级别”为 Information 且“类别”为 TodoApiSample.Pages.AboutModel 的日志 :The following Razor Pages example creates logs with Information as the level and TodoApiSample.Pages.AboutModel as the category:

public class AboutModel : PageModel
{
    private readonly ILogger _logger;

    public AboutModel(ILogger<AboutModel> logger)
    {
        _logger = logger;
    }
public void OnGet()
{
    Message = $"About page visited at {DateTime.UtcNow.ToLongTimeString()}";
    _logger.LogInformation("Message displayed: {Message}", Message);
}
public class TodoController : Controller
{
    private readonly ITodoRepository _todoRepository;
    private readonly ILogger _logger;

    public TodoController(ITodoRepository todoRepository,
        ILogger<TodoController> logger)
    {
        _todoRepository = todoRepository;
        _logger = logger;
    }
public IActionResult GetById(string id)
{
    _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
    var item = _todoRepository.Find(id);
    if (item == null)
    {
        _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
        return NotFound();
    }
    return new ObjectResult(item);
}

上述示例创建了“级别”为 InformationWarning,且“类别”为 TodoController 的日志 。The preceding example creates logs with Information and Warning as the level and TodoController class as the category.

日志“级别”代表所记录事件的严重程度 。The Log level indicates the severity of the logged event. 日志“类别”是与每个日志关联的字符串 。The log category is a string that is associated with each log. ILogger<T> 实例会创建“类别”为类型 T 的完全限定名称的日志。The ILogger<T> instance creates logs that have the fully qualified name of type T as the category. 本文稍后部分将更详细地介绍级别类别Levels and categories are explained in more detail later in this article.

启动时创建日志Create logs in Startup

要将日志写入 Startup 类,构造函数签名需包含 ILogger 参数:To write logs in the Startup class, include an ILogger parameter in the constructor signature:

public class Startup
{
    private readonly ILogger _logger;

    public Startup(IConfiguration configuration, ILogger<Startup> logger)
    {
        Configuration = configuration;
        _logger = logger;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        // Add our repository type
        services.AddSingleton<ITodoRepository, TodoRepository>();
        _logger.LogInformation("Added TodoRepository to services");
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            _logger.LogInformation("In Development environment");
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc();
    }
}

在程序中创建日志Create logs in Program

要将日志写入 Program 类,请从 DI 获取 ILogger 实例:To write logs in the Program class, get an ILogger instance from DI:

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();

    var todoRepository = host.Services.GetRequiredService<ITodoRepository>();
    todoRepository.Add(new Core.Model.TodoItem() { Name = "Feed the dog" });
    todoRepository.Add(new Core.Model.TodoItem() { Name = "Walk the dog" });

    var logger = host.Services.GetRequiredService<ILogger<Program>>();
    logger.LogInformation("Seeded the database.");

    host.Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();
        });

没有异步记录器方法No asynchronous logger methods

日志记录应该会很快,不值得牺牲性能来使用异步代码。Logging should be so fast that it isn't worth the performance cost of asynchronous code. 如果你的日志数据存储很慢,请不要直接写入它。If your logging data store is slow, don't write to it directly. 首先考虑将日志消息写入快速存储,稍后再将其变为慢速存储。Consider writing the log messages to a fast store initially, then move them to the slow store later. 例如,如果你要记录到 SQL Server,你可能不想直接在 Log 方法中记录,因为 Log 方法是同步的。For example, if you're logging to SQL Server, you don't want to do that directly in a Log method, since the Log methods are synchronous. 相反,你会将日志消息同步添加到内存中的队列,并让后台辅助线程从队列中拉出消息,以完成将数据推送到 SQL Server 的异步工作。Instead, synchronously add log messages to an in-memory queue and have a background worker pull the messages out of the queue to do the asynchronous work of pushing data to SQL Server.

ConfigurationConfiguration

日志记录提供程序配置由一个或多个配置提供程序提供:Logging provider configuration is provided by one or more configuration providers:

  • 文件格式(INI、JSON 和 XML)。File formats (INI, JSON, and XML).
  • 命令行参数。Command-line arguments.
  • 环境变量。Environment variables.
  • 内存中的 .NET 对象。In-memory .NET objects.
  • 未加密的机密管理器存储。The unencrypted Secret Manager storage.
  • 加密的用户存储,如 Azure Key VaultAn encrypted user store, such as Azure Key Vault.
  • (已安装或已创建的)自定义提供程序。Custom providers (installed or created).

例如,日志记录配置通常由应用设置文件的 Logging 部分提供。For example, logging configuration is commonly provided by the Logging section of app settings files. 以下示例显示了典型 appsettings.Development.json 文件的内容:The following example shows the contents of a typical appsettings.Development.json file:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    },
    "Console":
    {
      "IncludeScopes": true
    }
  }
}

Logging 属性可具有 LogLevel 和日志提供程序属性(显示控制台)。The Logging property can have LogLevel and log provider properties (Console is shown).

Logging 下的 LogLevel 属性指定了用于记录所选类别的最低级别The LogLevel property under Logging specifies the minimum level to log for selected categories. 在本例中,SystemMicrosoft 类别在 Information 级别记录,其他均在 Debug 级别记录。In the example, System and Microsoft categories log at Information level, and all others log at Debug level.

Logging 下的其他属性均指定了日志记录提供程序。Other properties under Logging specify logging providers. 本示例针对控制台提供程序。The example is for the Console provider. 如果提供程序支持日志作用域,则 IncludeScopes 将指示是否启用这些域。If a provider supports log scopes, IncludeScopes indicates whether they're enabled. 提供程序属性(例如本例的 Console)也可指定 LogLevel 属性。A provider property (such as Console in the example) may also specify a LogLevel property. 提供程序下的 LogLevel 指定了该提供程序记录的级别。LogLevel under a provider specifies levels to log for that provider.

如果在 Logging.{providername}.LogLevel 中指定了级别,则这些级别将重写 Logging.LogLevel 中设置的所有内容。If levels are specified in Logging.{providername}.LogLevel, they override anything set in Logging.LogLevel.

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

LogLevel 项表示日志名称。LogLevel keys represent log names. Default 项适用于未显式列出的日志。The Default key applies to logs not explicitly listed. 其值表示应用于给定日志的日志级别The value represents the log level applied to the given log.

若要了解如何实现配置提供程序,请参阅 ASP.NET Core 中的配置For information on implementing configuration providers, see ASP.NET Core 中的配置.

日志记录输出示例Sample logging output

使用上一部分中显示的示例代码从命令行运行应用时,将在控制台中看到日志。With the sample code shown in the preceding section, logs appear in the console when the app is run from the command line. 以下是控制台输出示例:Here's an example of console output:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/api/todo/0
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Executing action method TodoApi.Controllers.TodoController.GetById (TodoApi) with arguments (0) - ModelState is Valid
info: TodoApi.Controllers.TodoController[1002]
      Getting item 0
warn: TodoApi.Controllers.TodoController[4000]
      GetById(0) NOT FOUND
info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
      Executing HttpStatusCodeResult, setting HTTP status code 404
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action TodoApi.Controllers.TodoController.GetById (TodoApi) in 42.9286ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 148.889ms 404

通过向 http://localhost:5000/api/todo/0 处的示例应用发出 HTTP Get 请求来生成前述日志。The preceding logs were generated by making an HTTP Get request to the sample app at http://localhost:5000/api/todo/0.

在 Visual Studio 中运行示例应用时,“调试”窗口中将显示如下日志:Here's an example of the same logs as they appear in the Debug window when you run the sample app in Visual Studio:

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:53104/api/todo/0  
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method TodoApi.Controllers.TodoController.GetById (TodoApi) with arguments (0) - ModelState is Valid
TodoApi.Controllers.TodoController:Information: Getting item 0
TodoApi.Controllers.TodoController:Warning: GetById(0) NOT FOUND
Microsoft.AspNetCore.Mvc.StatusCodeResult:Information: Executing HttpStatusCodeResult, setting HTTP status code 404
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action TodoApi.Controllers.TodoController.GetById (TodoApi) in 152.5657ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 316.3195ms 404

由上一部分所示的 ILogger 调用创建的日志是以“TodoApi.Controllers.TodoController”开头的。The logs that are created by the ILogger calls shown in the preceding section begin with "TodoApi.Controllers.TodoController". 以“Microsoft”类别开头的日志来自 ASP.NET Core 框架代码。The logs that begin with "Microsoft" categories are from ASP.NET Core framework code. ASP.NET Core 和应用程序代码使用相同的日志记录 API 和提供程序。ASP.NET Core and application code are using the same logging API and providers.

本文余下部分将介绍有关日志记录的某些详细信息及选项。The remainder of this article explains some details and options for logging.

NuGet 包NuGet packages

ILoggerILoggerFactory 接口位于 Microsoft.Extensions.Logging.Abstractions 中,其默认实现位于 Microsoft.Extensions.Logging 中。The ILogger and ILoggerFactory interfaces are in Microsoft.Extensions.Logging.Abstractions, and default implementations for them are in Microsoft.Extensions.Logging.

日志类别Log category

创建 ILogger 对象后,将为其指定“类别” 。When an ILogger object is created, a category is specified for it. 该类别包含在由此 ILogger 实例创建的每条日志消息中。That category is included with each log message created by that instance of ILogger. 类别可以是任何字符串,但约定需使用类名,例如“TodoApi.Controllers.TodoController”。The category may be any string, but the convention is to use the class name, such as "TodoApi.Controllers.TodoController".

使用 ILogger<T> 获取一个 ILogger 实例,该实例使用 T 的完全限定类型名称作为类别:Use ILogger<T> to get an ILogger instance that uses the fully qualified type name of T as the category:

public class TodoController : Controller
{
    private readonly ITodoRepository _todoRepository;
    private readonly ILogger _logger;

    public TodoController(ITodoRepository todoRepository,
        ILogger<TodoController> logger)
    {
        _todoRepository = todoRepository;
        _logger = logger;
    }
public class TodoController : Controller
{
    private readonly ITodoRepository _todoRepository;
    private readonly ILogger _logger;

    public TodoController(ITodoRepository todoRepository,
        ILogger<TodoController> logger)
    {
        _todoRepository = todoRepository;
        _logger = logger;
    }

要显式指定类别,请调用 ILoggerFactory.CreateLoggerTo explicitly specify the category, call ILoggerFactory.CreateLogger:

public class TodoController : Controller
{
    private readonly ITodoRepository _todoRepository;
    private readonly ILogger _logger;

    public TodoController(ITodoRepository todoRepository,
        ILoggerFactory logger)
    {
        _todoRepository = todoRepository;
        _logger = logger.CreateLogger("TodoApiSample.Controllers.TodoController");
    }
public class TodoController : Controller
{
    private readonly ITodoRepository _todoRepository;
    private readonly ILogger _logger;

    public TodoController(ITodoRepository todoRepository,
        ILoggerFactory logger)
    {
        _todoRepository = todoRepository;
        _logger = logger.CreateLogger("TodoApiSample.Controllers.TodoController");
    }

ILogger<T> 相当于使用 T 的完全限定类型名称来调用 CreateLoggerILogger<T> is equivalent to calling CreateLogger with the fully qualified type name of T.

日志级别Log level

每个日志都指定了一个 LogLevel 值。Every log specifies a LogLevel value. 日志级别指示严重性或重要程度。The log level indicates the severity or importance. 例如,可在方法正常结束时写入 Information 日志,在方法返回“404 找不到”状态代码时写入 Warning 日志 。For example, you might write an Information log when a method ends normally and a Warning log when a method returns a 404 Not Found status code.

下面的代码会创建 InformationWarning 日志:The following code creates Information and Warning logs:

public IActionResult GetById(string id)
{
    _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
    var item = _todoRepository.Find(id);
    if (item == null)
    {
        _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
        return NotFound();
    }
    return new ObjectResult(item);
}
public IActionResult GetById(string id)
{
    _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
    var item = _todoRepository.Find(id);
    if (item == null)
    {
        _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
        return NotFound();
    }
    return new ObjectResult(item);
}

在上述代码中,第一个参数是日志事件 IDIn the preceding code, the first parameter is the Log event ID. 第二个参数是消息模板,其中的占位符用于填写剩余方法形参提供的实参值。The second parameter is a message template with placeholders for argument values provided by the remaining method parameters. 稍后将在本文的消息模板部分介绍方法参数。The method parameters are explained in the message template section later in this article.

在方法名称中包含级别的日志方法(例如 LogInformationLogWarning)是 ILogger 的扩展方法Log methods that include the level in the method name (for example, LogInformation and LogWarning) are extension methods for ILogger. 这些方法会调用可接受 LogLevel 参数的 Log 方法。These methods call a Log method that takes a LogLevel parameter. 可直接调用 Log 方法而不调用其中某个扩展方法,但语法相对复杂。You can call the Log method directly rather than one of these extension methods, but the syntax is relatively complicated. 有关详细信息,请参阅 ILogger记录器扩展源代码For more information, see ILogger and the logger extensions source code.

ASP.NET Core 定义了以下日志级别(按严重性从低到高排列)。ASP.NET Core defines the following log levels, ordered here from lowest to highest severity.

  • 跟踪 = 0Trace = 0

    有关通常仅用于调试的信息。For information that's typically valuable only for debugging. 这些消息可能包含敏感应用程序数据,因此不得在生产环境中启用它们。These messages may contain sensitive application data and so shouldn't be enabled in a production environment. 默认情况下禁用。 Disabled by default.

  • 调试 = 1Debug = 1

    有关在开发和调试中可能有用的信息。For information that may be useful in development and debugging. 示例:Entering method Configure with flag set to true. 由于日志数量过多,因此仅当执行故障排除时,才在生产中启用 Debug 级别日志。Example: Entering method Configure with flag set to true. Enable Debug level logs in production only when troubleshooting, due to the high volume of logs.

  • 信息 = 2Information = 2

    用于跟踪应用的常规流。For tracking the general flow of the app. 这些日志通常有长期价值。These logs typically have some long-term value. 示例:Request received for path /api/todoExample: Request received for path /api/todo

  • 警告 = 3Warning = 3

    表示应用流中的异常或意外事件。For abnormal or unexpected events in the app flow. 可能包括不会中断应用运行但仍需调查的错误或其他条件。These may include errors or other conditions that don't cause the app to stop but might need to be investigated. Warning 日志级别常用于已处理的异常。Handled exceptions are a common place to use the Warning log level. 示例:FileNotFoundException for file quotes.txt.Example: FileNotFoundException for file quotes.txt.

  • 错误 = 4Error = 4

    表示无法处理的错误和异常。For errors and exceptions that cannot be handled. 这些消息指示的是当前活动或操作(例如当前 HTTP 请求)中的失败,而不是整个应用中的失败。These messages indicate a failure in the current activity or operation (such as the current HTTP request), not an app-wide failure. 日志消息示例:Cannot insert record due to duplicate key violation.Example log message: Cannot insert record due to duplicate key violation.

  • 严重 = 5Critical = 5

    需要立即关注的失败。For failures that require immediate attention. 例如数据丢失、磁盘空间不足。Examples: data loss scenarios, out of disk space.

使用日志级别控制写入到特定存储介质或显示窗口的日志输出量。Use the log level to control how much log output is written to a particular storage medium or display window. 例如:For example:

  • 在生产中,通过 Information 级别将 Trace 发送到卷数据存储。In production, send Trace through Information level to a volume data store. 通过 Critical 级别将 Warning 发送到值数据存储。Send Warning through Critical to a value data store.
  • 在开发过程中,通过Critical 级别将 Warning 发送到控制台,并在进行故障排除时通过 Information 级别添加 TraceDuring development, send Warning through Critical to the console, and add Trace through Information when troubleshooting.

本文稍后的日志筛选部分介绍如何控制提供程序处理的日志级别。The Log filtering section later in this article explains how to control which log levels a provider handles.

ASP.NET Core 为框架事件写入日志。ASP.NET Core writes logs for framework events. 本文前面部分提供的日志示例排除了低于 Information 级别的日志,因此未创建 DebugTrace 级别日志。The log examples earlier in this article excluded logs below Information level, so no Debug or Trace level logs were created. 以下示例介绍了通过运行配置为显示 Debug 日志的示例应用而生成的控制台日志:Here's an example of console logs produced by running the sample app configured to show Debug logs:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:62555/api/todo/0
dbug: Microsoft.AspNetCore.Routing.Tree.TreeRouter[1]
      Request successfully matched the route with name 'GetTodo' and template 'api/Todo/{id}'.
dbug: Microsoft.AspNetCore.Mvc.Internal.ActionSelector[2]
      Action 'TodoApi.Controllers.TodoController.Update (TodoApi)' with id '089d59b6-92ec-472d-b552-cc613dfd625d' did not match the constraint 'Microsoft.AspNetCore.Mvc.Internal.HttpMethodActionConstraint'
dbug: Microsoft.AspNetCore.Mvc.Internal.ActionSelector[2]
      Action 'TodoApi.Controllers.TodoController.Delete (TodoApi)' with id 'f3476abe-4bd9-4ad3-9261-3ead09607366' did not match the constraint 'Microsoft.AspNetCore.Mvc.Internal.HttpMethodActionConstraint'
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Executing action TodoApi.Controllers.TodoController.GetById (TodoApi)
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Executing action method TodoApi.Controllers.TodoController.GetById (TodoApi) with arguments (0) - ModelState is Valid
info: TodoApi.Controllers.TodoController[1002]
      Getting item 0
warn: TodoApi.Controllers.TodoController[4000]
      GetById(0) NOT FOUND
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action method TodoApi.Controllers.TodoController.GetById (TodoApi), returned result Microsoft.AspNetCore.Mvc.NotFoundResult.
info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
      Executing HttpStatusCodeResult, setting HTTP status code 404
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action TodoApi.Controllers.TodoController.GetById (TodoApi) in 0.8788ms
dbug: Microsoft.AspNetCore.Server.Kestrel[9]
      Connection id "0HL6L7NEFF2QD" completed keep alive response.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 2.7286ms 404

日志事件 IDLog event ID

每个日志都可指定一个事件 ID 。Each log can specify an event ID. 该示例应用通过使用本地定义的 LoggingEvents 类来执行此操作:The sample app does this by using a locally defined LoggingEvents class:

public IActionResult GetById(string id)
{
    _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
    var item = _todoRepository.Find(id);
    if (item == null)
    {
        _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
        return NotFound();
    }
    return new ObjectResult(item);
}
public class LoggingEvents
{
    public const int GenerateItems = 1000;
    public const int ListItems = 1001;
    public const int GetItem = 1002;
    public const int InsertItem = 1003;
    public const int UpdateItem = 1004;
    public const int DeleteItem = 1005;

    public const int GetItemNotFound = 4000;
    public const int UpdateItemNotFound = 4001;
}
public IActionResult GetById(string id)
{
    _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
    var item = _todoRepository.Find(id);
    if (item == null)
    {
        _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
        return NotFound();
    }
    return new ObjectResult(item);
}
public class LoggingEvents
{
    public const int GenerateItems = 1000;
    public const int ListItems = 1001;
    public const int GetItem = 1002;
    public const int InsertItem = 1003;
    public const int UpdateItem = 1004;
    public const int DeleteItem = 1005;

    public const int GetItemNotFound = 4000;
    public const int UpdateItemNotFound = 4001;
}

事件 ID 与一组事件相关联。An event ID associates a set of events. 例如,与在页面上显示项列表相关的所有日志可能是 1001。For example, all logs related to displaying a list of items on a page might be 1001.

日志记录提供程序可将事件 ID 存储在 ID 字段中,存储在日志记录消息中,或者不进行存储。The logging provider may store the event ID in an ID field, in the logging message, or not at all. 调试提供程序不显示事件 ID。The Debug provider doesn't show event IDs. 控制台提供程序在类别后的括号中显示事件 ID:The console provider shows event IDs in brackets after the category:

info: TodoApi.Controllers.TodoController[1002]
      Getting item invalidid
warn: TodoApi.Controllers.TodoController[4000]
      GetById(invalidid) NOT FOUND

日志消息模板Log message template

每个日志都会指定一个消息模板。Each log specifies a message template. 消息模板可包含要填写参数的占位符。The message template can contain placeholders for which arguments are provided. 请在占位符中使用名称而不是数字。Use names for the placeholders, not numbers.

public IActionResult GetById(string id)
{
    _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
    var item = _todoRepository.Find(id);
    if (item == null)
    {
        _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
        return NotFound();
    }
    return new ObjectResult(item);
}
public IActionResult GetById(string id)
{
    _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
    var item = _todoRepository.Find(id);
    if (item == null)
    {
        _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
        return NotFound();
    }
    return new ObjectResult(item);
}

占位符的顺序(而非其名称)决定了为其提供值的参数。The order of placeholders, not their names, determines which parameters are used to provide their values. 在以下代码中,请注意消息模板中的参数名称未按顺序排列:In the following code, notice that the parameter names are out of sequence in the message template:

string p1 = "parm1";
string p2 = "parm2";
_logger.LogInformation("Parameter values: {p2}, {p1}", p1, p2);

此代码创建了一个参数值按顺序排列的日志消息:This code creates a log message with the parameter values in sequence:

Parameter values: parm1, parm2

日志记录框架按此方式工作,这样日志记录提供程序即可实现语义日志记录,也称为结构化日志记录The logging framework works this way so that logging providers can implement semantic logging, also known as structured logging. 参数本身会传递给日志记录系统,而不仅仅是格式化的消息模板。The arguments themselves are passed to the logging system, not just the formatted message template. 通过此信息,日志记录提供程序能够将参数值存储为字段。This information enables logging providers to store the parameter values as fields. 例如,假设记录器方法调用如下所示:For example, suppose logger method calls look like this:

_logger.LogInformation("Getting item {ID} at {RequestTime}", id, DateTime.Now);

如果要将日志发送到 Azure 表存储,则每个 Azure 表实体都可具有 IDRequestTime 属性,这简化了对日志数据的查询。If you're sending the logs to Azure Table Storage, each Azure Table entity can have ID and RequestTime properties, which simplifies queries on log data. 无需分析文本消息的超时,查询即可找到特定 RequestTime 范围内的全部日志。A query can find all logs within a particular RequestTime range without parsing the time out of the text message.

日志记录异常Logging exceptions

记录器方法有可传入异常的重载,如下方示例所示:The logger methods have overloads that let you pass in an exception, as in the following example:

catch (Exception ex)
{
    _logger.LogWarning(LoggingEvents.GetItemNotFound, ex, "GetById({ID}) NOT FOUND", id);
    return NotFound();
}
return new ObjectResult(item);
catch (Exception ex)
{
    _logger.LogWarning(LoggingEvents.GetItemNotFound, ex, "GetById({ID}) NOT FOUND", id);
    return NotFound();
}
return new ObjectResult(item);

不同的提供程序处理异常信息的方式不同。Different providers handle the exception information in different ways. 以下是上示代码的调试提供程序输出示例。Here's an example of Debug provider output from the code shown above.

TodoApi.Controllers.TodoController:Warning: GetById(036dd898-fb01-47e8-9a65-f92eb73cf924) NOT FOUND

System.Exception: Item not found exception.
 at TodoApi.Controllers.TodoController.GetById(String id) in C:\logging\sample\src\TodoApi\Controllers\TodoController.cs:line 226

日志筛选Log filtering

可为特定或所有提供程序和类别指定最低日志级别。You can specify a minimum log level for a specific provider and category or for all providers or all categories. 最低级别以下的日志不会传递给该提供程序,因此不会显示或存储它们。Any logs below the minimum level aren't passed to that provider, so they don't get displayed or stored.

要禁止显示所有日志,可将 LogLevel.None 指定为最低日志级别。To suppress all logs, specify LogLevel.None as the minimum log level. LogLevel.None 的整数值为 6,它大于 LogLevel.Critical (5)。The integer value of LogLevel.None is 6, which is higher than LogLevel.Critical (5).

在配置中创建筛选规则Create filter rules in configuration

项目模板代码调用 CreateDefaultBuilder 来为控制台和调试提供程序设置日志记录。The project template code calls CreateDefaultBuilder to set up logging for the Console and Debug providers. CreateDefaultBuilder 方法还使用如下所示的代码,设置日志记录以查找 Logging 部分的配置:The CreateDefaultBuilder method also sets up logging to look for configuration in a Logging section, using code like the following:

public static void Main(string[] args)
{
    var webHost = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 
                      optional: true, reloadOnChange: true);
            config.AddEnvironmentVariables();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            // Requires `using Microsoft.Extensions.Logging;`
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();
}

配置数据按提供程序和类别指定最低日志级别,如下方示例所示:The configuration data specifies minimum log levels by provider and category, as in the following example:

{
  "Logging": {
    "Debug": {
      "LogLevel": {
        "Default": "Information"
      }
    },
    "Console": {
      "IncludeScopes": false,
      "LogLevel": {
        "Microsoft.AspNetCore.Mvc.Razor.Internal": "Warning",
        "Microsoft.AspNetCore.Mvc.Razor.Razor": "Debug",
        "Microsoft.AspNetCore.Mvc.Razor": "Error",
        "Default": "Information"
      }
    },
    "LogLevel": {
      "Default": "Debug"
    }
  }
}

此 JSON 将创建 6 条筛选规则:1 条用于调试提供程序, 4 条用于控制台提供程序, 1 条用于所有提供程序。This JSON creates six filter rules: one for the Debug provider, four for the Console provider, and one for all providers. 创建 ILogger 对象时,为每个提供程序选择一个规则。A single rule is chosen for each provider when an ILogger object is created.

代码中的筛选规则Filter rules in code

下面的示例演示了如何在代码中注册筛选规则:The following example shows how to register filter rules in code:

WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureLogging(logging =>
        logging.AddFilter("System", LogLevel.Debug)
               .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Trace));

第二个 AddFilter 使用类型名称来指定调试提供程序。The second AddFilter specifies the Debug provider by using its type name. 第一个 AddFilter 应用于全部提供程序,因为它未指定提供程序类型。The first AddFilter applies to all providers because it doesn't specify a provider type.

如何应用筛选规则How filtering rules are applied

先前示例中显示的配置数据和 AddFilter 代码会创建下表所示的规则。The configuration data and the AddFilter code shown in the preceding examples create the rules shown in the following table. 前六条由配置示例创建,后两条由代码示例创建。The first six come from the configuration example and the last two come from the code example.

数字Number 提供程序Provider 类别的开头为...Categories that begin with ... 最低日志级别Minimum log level
11 调试Debug 全部类别All categories 信息Information
22 控制台Console Microsoft.AspNetCore.Mvc.Razor.InternalMicrosoft.AspNetCore.Mvc.Razor.Internal 警告Warning
33 控制台Console Microsoft.AspNetCore.Mvc.Razor.RazorMicrosoft.AspNetCore.Mvc.Razor.Razor 调试Debug
44 控制台Console Microsoft.AspNetCore.Mvc.RazorMicrosoft.AspNetCore.Mvc.Razor ErrorError
55 控制台Console 全部类别All categories 信息Information
66 全部提供程序All providers 全部类别All categories 调试Debug
77 全部提供程序All providers 系统System 调试Debug
88 调试Debug MicrosoftMicrosoft 跟踪Trace

创建 ILogger 对象时,ILoggerFactory 对象将根据提供程序选择一条规则,将其应用于该记录器。When an ILogger object is created, the ILoggerFactory object selects a single rule per provider to apply to that logger. 将按所选规则筛选 ILogger 实例写入的所有消息。All messages written by an ILogger instance are filtered based on the selected rules. 从可用规则中为每个提供程序和类别对选择最具体的规则。The most specific rule possible for each provider and category pair is selected from the available rules.

在为给定的类别创建 ILogger 时,以下算法将用于每个提供程序:The following algorithm is used for each provider when an ILogger is created for a given category:

  • 选择匹配提供程序或其别名的所有规则。Select all rules that match the provider or its alias. 如果找不到任何匹配项,则选择提供程序为空的所有规则。If no match is found, select all rules with an empty provider.
  • 根据上一步的结果,选择具有最长匹配类别前缀的规则。From the result of the preceding step, select rules with longest matching category prefix. 如果找不到任何匹配项,则选择未指定类别的所有规则。If no match is found, select all rules that don't specify a category.
  • 如果选择了多条规则,则采用最后一条 。If multiple rules are selected, take the last one.
  • 如果未选择任何规则,则使用 MinimumLevelIf no rules are selected, use MinimumLevel.

假设你使用上述规则列表为类别“Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine”创建了 ILogger 对象:With the preceding list of rules, suppose you create an ILogger object for category "Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine":

  • 对于调试提供程序,规则 1、6 和 8 适用。For the Debug provider, rules 1, 6, and 8 apply. 规则 8 最为具体,因此选择了它。Rule 8 is most specific, so that's the one selected.
  • 对于控制台提供程序,符合的有规则 3、规则 4、规则 5 和规则 6。For the Console provider, rules 3, 4, 5, and 6 apply. 规则 3 最为具体。Rule 3 is most specific.

生成的 ILogger 实例将 Trace 级别及更高级别的日志发送到调试提供程序。The resulting ILogger instance sends logs of Trace level and above to the Debug provider. Debug 级别及更高级别的日志会发送到控制台提供程序。Logs of Debug level and above are sent to the Console provider.

提供程序别名Provider aliases

每个提供程序都定义了一个别名;可在配置中使用该别名来代替完全限定的类型名称 。Each provider defines an alias that can be used in configuration in place of the fully qualified type name. 对于内置提供程序,请使用以下别名:For the built-in providers, use the following aliases:

  • 控制台Console
  • 调试Debug
  • EventSourceEventSource
  • EventLogEventLog
  • TraceSourceTraceSource
  • AzureAppServicesFileAzureAppServicesFile
  • AzureAppServicesBlobAzureAppServicesBlob
  • ApplicationInsightsApplicationInsights

默认最低级别Default minimum level

仅当配置或代码中的规则对给定提供程序和类别都不适用时,最低级别设置才会生效。There's a minimum level setting that takes effect only if no rules from configuration or code apply for a given provider and category. 下面的示例演示如何设置最低级别:The following example shows how to set the minimum level:

WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Warning));

如果没有明确设置最低级别,则默认值为 Information,它表示 TraceDebug 日志将被忽略。If you don't explicitly set the minimum level, the default value is Information, which means that Trace and Debug logs are ignored.

筛选器函数Filter functions

对配置或代码没有向其分配规则的所有提供程序和类别调用筛选器函数。A filter function is invoked for all providers and categories that don't have rules assigned to them by configuration or code. 函数中的代码可访问提供程序类型、类别和日志级别。Code in the function has access to the provider type, category, and log level. 例如:For example:

WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureLogging(logBuilder =>
    {
        logBuilder.AddFilter((provider, category, logLevel) =>
        {
            if (provider == "Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider" &&
                category == "TodoApiSample.Controllers.TodoController")
            {
                return false;
            }
            return true;
        });
    });

通过某些日志记录提供程序,可根据日志级别和类别指定何时向存储介质写入日志、何时忽略日志。Some logging providers let you specify when logs should be written to a storage medium or ignored based on log level and category.

AddConsoleAddDebug 扩展方法提供了接受筛选条件的重载。The AddConsole and AddDebug extension methods provide overloads that accept filtering criteria. 下列示例代码将使控制台提供程序忽略低于 Warning 级别的日志,而使调试提供程序忽略由框架创建的日志。The following sample code causes the console provider to ignore logs below Warning level, while the Debug provider ignores logs that the framework creates.

public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory
        .AddConsole(LogLevel.Warning)
        .AddDebug((category, logLevel) => (category.Contains("TodoApi") && logLevel >= LogLevel.Trace));

AddEventLog 方法拥有接受 EventLogSettings 实例的重载,该实例的 Filter 属性中可能包含筛选函数。The AddEventLog method has an overload that takes an EventLogSettings instance, which may contain a filtering function in its Filter property. TraceSource 提供程序不提供以上任何重载,因为其日志记录级别和其他参数都以它使用的 SourceSwitchTraceListener 为依据。The TraceSource provider doesn't provide any of those overloads, since its logging level and other parameters are based on the SourceSwitch and TraceListener it uses.

可使用 WithFilter 扩展方法为所有通过 ILoggerFactory 实例注册的提供程序设置筛选规则。To set filtering rules for all providers that are registered with an ILoggerFactory instance, use the WithFilter extension method. 下面的示例将(类别以“Microsoft”或“System”开头的)框架日志限制为警告,并在调试级别记录应用程序代码创建的日志。The example below limits framework logs (category begins with "Microsoft" or "System") to warnings while logging at debug level for logs created by application code.

public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory
        .WithFilter(new FilterLoggerSettings
        {
            { "Microsoft", LogLevel.Warning },
            { "System", LogLevel.Warning },
            { "ToDoApi", LogLevel.Debug }
        })
        .AddConsole()
        .AddDebug();

要防止写入任何日志,请将 LogLevel.None 指定为最低日志级别。To prevent any logs from being written, specify LogLevel.None as the minimum log level. LogLevel.None 的整数值为 6,它大于 LogLevel.Critical (5)。The integer value of LogLevel.None is 6, which is higher than LogLevel.Critical (5).

WithFilter 扩展方法由 Microsoft.Extensions.Logging.Filter NuGet 包提供。The WithFilter extension method is provided by the Microsoft.Extensions.Logging.Filter NuGet package. 该方法返回一个新的 ILoggerFactory 实例,该实例将筛选传递给注册的所有记录器提供程序的日志消息。The method returns a new ILoggerFactory instance that will filter the log messages passed to all logger providers registered with it. 它不会影响其他任何 ILoggerFactory 实例,包括原始 ILoggerFactory 实例。It doesn't affect any other ILoggerFactory instances, including the original ILoggerFactory instance.

系统类别和级别System categories and levels

下面是 ASP.NET Core 和 Entity Framework Core 使用的一些类别,备注中说明了可从这些类别获取的具体日志:Here are some categories used by ASP.NET Core and Entity Framework Core, with notes about what logs to expect from them:

类别Category 说明Notes
Microsoft.AspNetCoreMicrosoft.AspNetCore 常规 ASP.NET Core 诊断。General ASP.NET Core diagnostics.
Microsoft.AspNetCore.DataProtectionMicrosoft.AspNetCore.DataProtection 考虑、找到并使用了哪些密钥。Which keys were considered, found, and used.
Microsoft.AspNetCore.HostFilteringMicrosoft.AspNetCore.HostFiltering 所允许的主机。Hosts allowed.
Microsoft.AspNetCore.HostingMicrosoft.AspNetCore.Hosting HTTP 请求完成的时间和启动时间。How long HTTP requests took to complete and what time they started. 加载了哪些承载启动程序集。Which hosting startup assemblies were loaded.
Microsoft.AspNetCore.MvcMicrosoft.AspNetCore.Mvc MVC 和 Razor 诊断。MVC and Razor diagnostics. 模型绑定、筛选器执行、视图编译和操作选择。Model binding, filter execution, view compilation, action selection.
Microsoft.AspNetCore.RoutingMicrosoft.AspNetCore.Routing 路由匹配信息。Route matching information.
Microsoft.AspNetCore.ServerMicrosoft.AspNetCore.Server 连接启动、停止和保持活动响应。Connection start, stop, and keep alive responses. HTTP 证书信息。HTTPS certificate information.
Microsoft.AspNetCore.StaticFilesMicrosoft.AspNetCore.StaticFiles 提供的文件。Files served.
Microsoft.EntityFrameworkCoreMicrosoft.EntityFrameworkCore 常规 Entity Framework Core 诊断。General Entity Framework Core diagnostics. 数据库活动和配置、更改检测、迁移。Database activity and configuration, change detection, migrations.

日志作用域Log scopes

“作用域”可对一组逻辑操作分组 。A scope can group a set of logical operations. 此分组可用于将相同的数据附加到作为集合的一部分而创建的每个日志。This grouping can be used to attach the same data to each log that's created as part of a set. 例如,在处理事务期间创建的每个日志都可包括事务 ID。For example, every log created as part of processing a transaction can include the transaction ID.

范围是由 BeginScope 方法返回的 IDisposable 类型,持续至释放为止。A scope is an IDisposable type that's returned by the BeginScope method and lasts until it's disposed. 要使用作用域,请在 using 块中包装记录器调用:Use a scope by wrapping logger calls in a using block:

public IActionResult GetById(string id)
{
    TodoItem item;
    using (_logger.BeginScope("Message attached to logs created in the using block"))
    {
        _logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
        item = _todoRepository.Find(id);
        if (item == null)
        {
            _logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
            return NotFound();
        }
    }
    return new ObjectResult(item);
}

下列代码为控制台提供程序启用作用域:The following code enables scopes for the console provider:

Program.cs :Program.cs:

.ConfigureLogging((hostingContext, logging) =>
{
    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
    logging.AddConsole(options => options.IncludeScopes = true);
    logging.AddDebug();
})

备注

要启用基于作用域的日志记录,必须先配置 IncludeScopes 控制台记录器选项。Configuring the IncludeScopes console logger option is required to enable scope-based logging.

若要了解关配置,请参阅配置部分。For information on configuration, see the Configuration section.

Program.cs :Program.cs:

.ConfigureLogging((hostingContext, logging) =>
{
    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
    logging.AddConsole(options => options.IncludeScopes = true);
    logging.AddDebug();
})

备注

要启用基于作用域的日志记录,必须先配置 IncludeScopes 控制台记录器选项。Configuring the IncludeScopes console logger option is required to enable scope-based logging.

Startup.csStartup.cs:

public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory
        .AddConsole(includeScopes: true)
        .AddDebug();

每条日志消息都包含作用域内的信息:Each log message includes the scoped information:

info: TodoApi.Controllers.TodoController[1002]
      => RequestId:0HKV9C49II9CK RequestPath:/api/todo/0 => TodoApi.Controllers.TodoController.GetById (TodoApi) => Message attached to logs created in the using block
      Getting item 0
warn: TodoApi.Controllers.TodoController[4000]
      => RequestId:0HKV9C49II9CK RequestPath:/api/todo/0 => TodoApi.Controllers.TodoController.GetById (TodoApi) => Message attached to logs created in the using block
      GetById(0) NOT FOUND

内置日志记录提供程序Built-in logging providers

ASP.NET Core 提供以下提供程序:ASP.NET Core ships the following providers:

有关 stdout 日志记录的信息,请参阅 对 IIS 上的 ASP.NET Core 进行故障排除对 Azure 应用服务上的 ASP.NET Core 进行故障排除For information about stdout logging, see 对 IIS 上的 ASP.NET Core 进行故障排除 and 对 Azure 应用服务上的 ASP.NET Core 进行故障排除.

控制台提供程序Console provider

Microsoft.Extensions.Logging.Console 提供程序包向控制台发送日志输出。The Microsoft.Extensions.Logging.Console provider package sends log output to the console.

logging.AddConsole();
loggerFactory.AddConsole();

通过 AddConsole 重载,可传入一个最低日志级别、一个筛选器函数,以及一个用于指示作用域是否受支持的布尔值。AddConsole overloads let you pass in a minimum log level, a filter function, and a boolean that indicates whether scopes are supported. 另一个选项是传递 IConfiguration 对象,可通过它来指定支持的作用域及日志记录级别。Another option is to pass in an IConfiguration object, which can specify scopes support and logging levels.

关于控制台提供程序选项,请参阅 ConsoleLoggerOptionsFor Console provider options, see ConsoleLoggerOptions.

控制台提供程序对性能有重大影响,通常不适合在生产中使用。The console provider has a significant impact on performance and is generally not appropriate for use in production.

在 Visual Studio 中创建新项目时,AddConsole 方法如下所示:When you create a new project in Visual Studio, the AddConsole method looks like this:

loggerFactory.AddConsole(Configuration.GetSection("Logging"));

此代码引用 appSettings.json 文件的 Logging 部分: This code refers to the Logging section of the appSettings.json file:

{
  "Logging": {
    "Console": {
      "IncludeScopes": false
    },
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

所显示的设置将框架日志限制为警告,并允许在调试级别记录应用日志,如日志筛选部分所述。The settings shown limit framework logs to warnings while allowing the app to log at debug level, as explained in the Log filtering section. 有关详细信息,请参阅配置For more information, see Configuration.

要查看控制台日志记录输出,请在项目文件夹中打开命令提示符并运行以下命令:To see console logging output, open a command prompt in the project folder and run the following command:

dotnet run

调试提供程序Debug provider

Microsoft.Extensions.Logging.Debug 提供程序包使用 System.Diagnostics.Debug 类(Debug.WriteLine 方法调用)来写入日志输出。The Microsoft.Extensions.Logging.Debug provider package writes log output by using the System.Diagnostics.Debug class (Debug.WriteLine method calls).

在 Linux 中,此提供程序将日志写入 /var/log/message 。On Linux, this provider writes logs to /var/log/message.

logging.AddDebug();
loggerFactory.AddDebug();

AddDebug 重载允许传入最低日志级别或筛选器函数。AddDebug overloads let you pass in a minimum log level or a filter function.

EventSource 提供程序EventSource provider

对于面向 ASP.NET Core 1.1.0 或更高版本的应用,Microsoft.Extensions.Logging.EventSource 提供程序包可实现事件跟踪。For apps that target ASP.NET Core 1.1.0 or later, the Microsoft.Extensions.Logging.EventSource provider package can implement event tracing. 在 Windows 中,它使用 ETWOn Windows, it uses ETW. 提供程序可跨平台使用,但尚无支持 Linux 或 macOS 的事件集合和显示工具。The provider is cross-platform, but there are no event collection and display tools yet for Linux or macOS.

logging.AddEventSourceLogger();
loggerFactory.AddEventSourceLogger();

可使用 PerfView 实用工具收集和查看日志。A good way to collect and view logs is to use the PerfView utility. 虽然其他工具也可以查看 ETW 日志,但在处理由 ASP.NET 发出的 ETW 事件时,使用 PerfView 能获得最佳体验。There are other tools for viewing ETW logs, but PerfView provides the best experience for working with the ETW events emitted by ASP.NET.

要将 PerfView 配置为收集此提供程序记录的事件,请向 Additional Providers 列表添加字符串 *Microsoft-Extensions-LoggingTo configure PerfView for collecting events logged by this provider, add the string *Microsoft-Extensions-Logging to the Additional Providers list. (请勿遗漏字符串起始处的星号。)(Don't miss the asterisk at the start of the string.)

其他 Perfview 提供程序

Windows EventLog 提供程序Windows EventLog provider

Microsoft.Extensions.Logging.EventLog 提供程序包向 Windows 事件日志发送日志输出。The Microsoft.Extensions.Logging.EventLog provider package sends log output to the Windows Event Log.

logging.AddEventLog();
loggerFactory.AddEventLog();

AddEventLog 重载允许传入 EventLogSettings 或最低日志级别。AddEventLog overloads let you pass in EventLogSettings or a minimum log level.

TraceSource 提供程序TraceSource provider

Microsoft.Extensions.Logging.TraceSource 提供程序包使用 TraceSource 库和提供程序。The Microsoft.Extensions.Logging.TraceSource provider package uses the TraceSource libraries and providers.

logging.AddTraceSource(sourceSwitchName);
loggerFactory.AddTraceSource(sourceSwitchName);

AddTraceSource 重载 允许传入资源开关和跟踪侦听器。AddTraceSource overloads let you pass in a source switch and a trace listener.

要使用此提供程序,应用必须在 .NET Framework(而非 .NET Core)上运行。To use this provider, an app has to run on the .NET Framework (rather than .NET Core). 提供程序可将消息路由到多个侦听器,例如示例应用中使用的 TextWriterTraceListenerThe provider can route messages to a variety of listeners, such as the TextWriterTraceListener used in the sample app.

以下示例配置了 TraceSource 提供程序,用于向控制台窗口记录 Warning 和更高级别的消息。The following example configures a TraceSource provider that logs Warning and higher messages to the console window.

public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory
        .AddDebug();

    // add Trace Source logging
    var testSwitch = new SourceSwitch("sourceSwitch", "Logging Sample");
    testSwitch.Level = SourceLevels.Warning;
    loggerFactory.AddTraceSource(testSwitch,
        new TextWriterTraceListener(writer: Console.Out));

Azure 应用服务提供程序Azure App Service provider

Microsoft.Extensions.Logging.AzureAppServices 提供程序包将日志写入 Azure App Service 应用的文件系统,以及 Azure 存储帐户中的 blob 存储The Microsoft.Extensions.Logging.AzureAppServices provider package writes logs to text files in an Azure App Service app's file system and to blob storage in an Azure Storage account. 面向 .NET Core 1.1 或更高版本的应用可使用该提供程序包。The provider package is available for apps targeting .NET Core 1.1 or later.

如果面向 .NET Core,请注意以下几点:If targeting .NET Core, note the following points:

如果面向 .NET Framework 或引用 Microsoft.AspNetCore.App 元包,请向项目添加提供程序包。If targeting .NET Framework or referencing the Microsoft.AspNetCore.App metapackage, add the provider package to the project. 调用 AddAzureWebAppDiagnosticsInvoke AddAzureWebAppDiagnostics:

logging.AddAzureWebAppDiagnostics();
loggerFactory.AddAzureWebAppDiagnostics();

AddAzureWebAppDiagnostics 重载允许传入 AzureAppServicesDiagnosticsSettingsAn AddAzureWebAppDiagnostics overload lets you pass in AzureAppServicesDiagnosticsSettings. 设置对象可以覆盖默认设置,例如日志记录输出模板、blob 名称和文件大小限制。The settings object can override default settings, such as the logging output template, blob name, and file size limit. (“输出模板”是一个消息模板,除了通过 ILogger 方法调用提供的内容之外,还可将其应用于所有日志。 )(Output template is a message template that's applied to all logs in addition to what's provided with an ILogger method call.)

要配置提供程序设置,请使用 AzureFileLoggerOptionsAzureBlobLoggerOptions,如以下示例所示:To configure provider settings, use AzureFileLoggerOptions and AzureBlobLoggerOptions, as shown in the following example:

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();

    var todoRepository = host.Services.GetRequiredService<ITodoRepository>();
    todoRepository.Add(new Core.Model.TodoItem() { Name = "Feed the dog" });
    todoRepository.Add(new Core.Model.TodoItem() { Name = "Walk the dog" });

    var logger = host.Services.GetRequiredService<ILogger<Program>>();
    logger.LogInformation("Seeded the database.");

    host.Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging(logging => logging.AddAzureWebAppDiagnostics())
        .ConfigureServices(serviceCollection => serviceCollection
                .Configure<AzureFileLoggerOptions>(options =>
                {
                    options.FileName = "azure-diagnostics-";
                    options.FileSizeLimit = 50 * 1024;
                    options.RetainedFileCountLimit = 5;
                }).Configure<AzureBlobLoggerOptions>(options =>
                {
                    options.BlobName = "log.txt";
                }))
        .UseStartup<Startup>();

在部署应用服务应用时,应用程序将采用 Azure 门户中“应用服务”页面下的应用服务日志部分的设置 。When you deploy to an App Service app, the application honors the settings in the App Service logs section of the App Service page of the Azure portal. 更新以下设置后,更改立即生效,无需重启或重新部署应用。When the following settings are updated, the changes take effect immediately without requiring a restart or redeployment of the app.

  • 应用程序日志记录(Filesystem) Application Logging (Filesystem)
  • 应用程序日志记录(Blob) Application Logging (Blob)

日志文件的默认位置是 D:\home\LogFiles\Application 文件夹,默认文件名为 diagnostics-yyyymmdd.txt 。The default location for log files is in the D:\home\LogFiles\Application folder, and the default file name is diagnostics-yyyymmdd.txt. 默认文件大小上限为 10 MB,默认最大保留文件数为 2。The default file size limit is 10 MB, and the default maximum number of files retained is 2. 默认 blob 名为 {app-name}{timestamp}/yyyy/mm/dd/hh/{guid}-applicationLog.txt 。The default blob name is {app-name}{timestamp}/yyyy/mm/dd/hh/{guid}-applicationLog.txt.

该提供程序仅当项目在 Azure 环境中运行时有效。The provider only works when the project runs in the Azure environment. 项目在本地运行时,该提供程序无效 — 它不会写入本地文件或 blob 的本地开发存储。It has no effect when the project is run locally—it doesn't write to local files or local development storage for blobs.

Azure 日志流式处理Azure log streaming

通过 Azure 日志流式处理,可从以下位置实时查看日志活动:Azure log streaming lets you view log activity in real time from:

  • 应用服务器The app server
  • Web 服务器The web server
  • 请求跟踪失败Failed request tracing

要配置 Azure 日志流式处理,请执行以下操作:To configure Azure log streaming:

  • 从应用的门户页导航到“应用服务日志”页 。Navigate to the App Service logs page from your app's portal page.
  • 将“应用程序日志记录(Filesystem)”设置为“开” 。Set Application Logging (Filesystem) to On.
  • 选择日志级别 。Choose the log Level.

导航到“日志流”页面来查看应用消息 。Navigate to the Log Stream page to view app messages. 它们由应用通过 ILogger 接口记录。They're logged by the app through the ILogger interface.

Azure Application Insights 跟踪日志记录Azure Application Insights trace logging

Microsoft.Extensions.Logging.ApplicationInsights 提供程序包将日志写入 Azure Application Insights。The Microsoft.Extensions.Logging.ApplicationInsights provider package writes logs to Azure Application Insights. Application Insights 是一项服务,可监视 Web 应用并提供用于查询和分析遥测数据的工具。Application Insights is a service that monitors a web app and provides tools for querying and analyzing the telemetry data. 如果使用此提供程序,则可以使用 Application Insights 工具来查询和分析日志。If you use this provider, you can query and analyze your logs by using the Application Insights tools.

日志记录提供程序作为 Microsoft.ApplicationInsights.AspNetCore(这是提供 ASP.NET Core 的所有可用遥测的包)的依赖项包括在内。The logging provider is included as a dependency of Microsoft.ApplicationInsights.AspNetCore, which is the package that provides all available telemetry for ASP.NET Core. 如果使用此包,则无需安装提供程序包。If you use this package, you don't have to install the provider package.

请勿使用用于 ASP.NET 4.x 的 Microsoft.ApplicationInsights.Web 包—。Don't use the Microsoft.ApplicationInsights.Web package—that's for ASP.NET 4.x.

有关更多信息,请参见以下资源:For more information, see the following resources:

备注

截至 2019 年 5 月 1 日,标题为用于 ASP.NET Core 的 Application Insights 的文章已过期,教程步骤不起作用。As of 5/1/2019, the article titled Application Insights for ASP.NET Core is out of date, and the tutorial steps don't work. 请改为参阅用于 ASP.NET Core 应用程序的 Application InsightsRefer to Application Insights for ASP.NET Core applications instead. 我们已经注意到此问题,正努力更正该问题。We are aware of the issue and are working to correct it.

第三方日志记录提供程序Third-party logging providers

适用于 ASP.NET Core 的第三方日志记录框架:Third-party logging frameworks that work with ASP.NET Core:

某些第三方框架可以执行语义日志记录(又称结构化日志记录)Some third-party frameworks can perform semantic logging, also known as structured logging.

使用第三方框架类似于使用以下内置提供程序之一:Using a third-party framework is similar to using one of the built-in providers:

  1. 将 NuGet 包添加到你的项目。Add a NuGet package to your project.
  2. 调用 ILoggerFactoryCall an ILoggerFactory.

有关详细信息,请参阅各提供程序的相关文档。For more information, see each provider's documentation. Microsoft 不支持第三方日志记录提供程序。Third-party logging providers aren't supported by Microsoft.

其他资源Additional resources