ILogger 和 ILoggerFactory 接口位于 Microsoft.Extensions.Logging.Abstractions 中,其默认实现位于 Microsoft.Extensions.Logging 中。
简单使用
在 StartUp 中进行配置:
public class Program{public static void Main(string[] args){CreateWebHostBuilder(args).Build().Run();}public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().ConfigureLogging(logging =>{logging.ClearProviders();logging.AddConsole();});}
在 Controller 中使用:
public class TodoController : ControllerBase{private readonly TodoContext _context;private readonly ILogger _logger;public TodoController(TodoContext context,ILogger<TodoController> logger){_context = context;_logger = logger;if (!_context.TodoItems.Any()){_context.TodoItems.Add(new TodoItem { Name = "Item1" });_context.SaveChanges();}}[HttpGet]public ActionResult<List<TodoItem>> GetAll(){_logger.LogInformation("Get All ToDo Items");return _context.TodoItems.ToList();}...}
在输出中查看:
高级设置
配置
appsettings.json:
{"Logging": {"LogLevel": {"Default": "Debug","System": "Information","Microsoft": "Information"},"Console": {"IncludeScopes": true}},"AllowedHosts": "*"}
在 Program 中加载配置:
public static void Main(string[] args){var webHost = WebHost.CreateDefaultBuilder(args).UseContentRoot(Directory.GetCurrentDirectory()).ConfigureAppConfiguration((hostingContext, config) =>{config.AddJsonFile("appsettings.json", true, true);config.AddEnvironmentVariables();}).ConfigureLogging((hostingContext, logging) =>{logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));logging.AddConsole();logging.AddEventSourceLogger();}).UseStartup<Startup>().Build();webHost.Run();}
日志作用域
“作用域”可对一组逻辑操作分组。 此分组可用于将相同的数据附加到作为集合的一部分而创建的每个日志。
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);}
为 Console Log 启用作用域:
.ConfigureLogging((hostingContext, logging) =>{logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));logging.AddConsole(options => options.IncludeScopes = true);logging.AddDebug();})
未启用作用域时:
启用后:
第三方日志记录提供程序
适用于 ASP.NET Core 的第三方日志记录框架:
- elmah.io(GitHub 存储库)
- Gelf(GitHub 存储库)
- JSNLog(GitHub 存储库)
- KissLog.net(GitHub 存储库)
- Loggr(GitHub 存储库)
- NLog(GitHub 存储库)
- Sentry(GitHub 存储库)
- Serilog(GitHub 存储库)
- Stackdriver(Github 存储库)
某些第三方框架可以执行语义日志记录(又称结构化日志记录)。
使用第三方框架的步骤类似于使用内置提供程序:
- 将 NuGet 包添加到你的项目
- 调用
ILoggerFactory
