Dotnet Core Console App 使用 ILogger 依赖注入

ASP.NET Core 可以很轻松的在模板上依赖注入日志模块 ILogger,但是对于控制台应用(Console App)ILogger 就不是那么友好,想要在 Console App 使用日志模块,需要手动构建依赖注入环境

环境

  • Dotnet Core 3.1
  • VS2019

参考

步骤

添加 Nuget 包

在项目内添加包:

  • Microsoft.Extensions.DependencyInjection
  • Microsoft.Extensions.Logging
  • Microsoft.Extensions.Logging.Console

配置 ILogger 模块的依赖注入

以 Dotnet Core Console App 模板为例,代码如下

using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace ILogger-Test{
    class Program {
        #region DI variables
        private readonly ILogger _logger;
        #endregion

        public Program(ILogger<Program> logger) {
            _logger = logger;
        }

        private static void ConfigureServices(ServiceCollection services) {
            services.AddLogging(logging => {
                //logging.AddFilter("Program", LogLevel.Debug);
                logging.AddFilter("System", LogLevel.Warning);
                logging.AddFilter("Microsoft", LogLevel.Warning);
                logging.AddConsole();
            }).AddTransient<Program>();
        }
        
        internal async Task Run() {
            _logger.LogInformation(DateTime.Now.ToString() + " - Start Job -");
            
            //...

            _logger.LogInformation(DateTime.Now.ToString() + " - End Job -");
        }

        static async Task Main() {
            #region config service
            var services = new ServiceCollection();
            ConfigureServices(services);
            using (ServiceProvider serviceProvider = services.BuildServiceProvider()) {
                Program app = serviceProvider.GetService<Program>();
                await app.Run();
            }
            #endregion
        }
    }
}

效果

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据