将日志(Microsoft.Extensions.Logging)添加到.NET Core控制台应用程序
在.NET Core项目中,日志记录是通过依赖项注入进行管理的。 尽管这对于ASP.NET项目效果很好,但在启动Startup.cs中的新项目时,所有这些都会自动创建,而在控制台应用程序中则需要一些配置才能使其启动并运行。
这大部分是从此处的博客文章整理而成的,但我对其进行了修改。
该项目是在Visual Studio 2019中创建的,并且需要以下程序包(在csproj文件中找到)
<ItemGroup> <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.1.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.0" /> </ItemGroup>
该项目中的业务逻辑在服务中得到处理,而Program.cs用于引导运行应用程序所需的一切。 需要在app-settings.json的“ ConnectionStrings”部分中添加一个“Logging”配置,该条目可以像这样添加到控制台应用程序中。
app-settings.json
{ "Logging": { "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" }, "Console": { "IncludeScopes": true } } }
Program.cs
public class Program { public static void Main(string[] args) { var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); var run = serviceProvider.GetService<App>(); if (run != null) run.Run(); else System.Console.WriteLine("Init Error"); } private static void ConfigureServices(IServiceCollection services) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("app-settings.json", false) .Build(); services.AddLogging(loggingBuilder => { loggingBuilder.AddConfiguration(configuration.GetSection("Logging")); loggingBuilder.AddConsole(); loggingBuilder.AddDebug(); }); // Add access to generic IConfigurationRoot services.AddSingleton(configuration); // Add services services.AddTransient<IBackupService, BackupService>(); // Add app services.AddTransient<App>(); } }
App.cs
public class App { private readonly IBackupService _backupService; private readonly ILogger<App> _logger; private readonly IConfigurationRoot _config; public App(ILogger<App> logger, IBackupService backupService, IConfigurationRoot config) { _logger = logger; _backupService = backupService; _config = config; } public void Run() { _logger.LogInformation($"Running application."); _backupService.Run(); System.Console.ReadKey(); } }
BackupService.cs
public interface IBackupService { void Run(); } public class BackupService : IBackupService { private readonly ILogger<BackupService> _logger; private readonly IConfigurationRoot _config; public BackupService(ILogger<BackupService> logger, IConfigurationRoot config) { _logger = logger; _config = config; } public void Run() { _logger.LogDebug($"Running backup service."); } }