Logging to Console with DI in C#

放肆的年华 提交于 2020-01-24 11:15:37

问题


in this short sample, if I keep just the .AddConsole() in ConfigureServices nothing gets logged to console regardless of the LogLevel, but if I add .AddConsole().AddDebug() all messages get logged to Console 3 times! What am I missing? Thanks!

namespace samples
{
    using System;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;

    public class Program
    {    
        public static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var app = serviceProvider.GetService<Application>();
            app.Run();
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            // Add Logger
            services.AddLogging(configure => configure.AddConsole().AddDebug());

            // Register Application
            services.AddTransient<Application>();
        }
    }

    public class Application {
        private readonly ILogger logger;

        public Application(ILogger<Application> logger)
        {
            this.logger = logger;
            this.logger.LogInformation("In Application::ctor");
        }

        public void Run() 
        {
            this.logger.LogInformation("Info: In Application::Run");
            this.logger.LogWarning("Warn: In Application::Run");
            this.logger.LogError("Error: In Application::Run");
            this.logger.LogCritical("Critical: In Application::Run");
        }
    }
}

And this is what gets displayed for each Log*() call:

fail: samples.Application[0]
      Error: In Application::Run
samples.Application: Error: Error: In Application::Run

Update/Solution Thanks @panoskarajohn for figuring this out. App.Run() needed to be an async: Change app.Run(); => Task.Run(() => app.Run()).Wait(); public void Run() => public async Task Run() And should work without debugging() option I cannot find anything on why this happens

Anyone knows why?


回答1:


I am not aware why this is not happening for the addDebug() option.

I suppose the AddDebug() has some special configuration, and flushes the output before the program exits. Please if you have any clues enlighten us.

Why the addConsole() does not work?

Console logging is happening on a background thread. So if the application exits too fast then the logger doesn't have time to log -> https://github.com/aspnet/Logging/issues/631

So it is not that it is not happening. It is that it does not have time to write to the console. The application exits too fast.

In order to fix this in your code. Add a Console.Read() at the end of your program so that it won't exit.

public static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var app = serviceProvider.GetService<Application>();
            app.Run();
            Console.Read(); // So the application will not exit and there will be time for the background thread to do its job
        }

Also i came across another solution which is create an asynchronous Task and wait upon it.

Update the code like this.

public static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var app = serviceProvider.GetService<Application>();
            Task.Run(() => app.Run()).Wait();
        }
// also update your Application run method
public async Task Run()
        {
            logger.LogInformation("Info: In Application::Run");
            logger.LogWarning("Warn: In Application::Run");
            logger.LogError("Error: In Application::Run");
            logger.LogCritical("Critical: In Application::Run");
        }

The end result should look like this.

public class Program
    {
        public static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var app = serviceProvider.GetService<Application>();
            Task.Run(() => app.Run()).Wait();
            Console.Read();
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            // Add Logger
            services.AddLogging(configure =>
            {
                configure.AddConsole();
            }).AddTransient<Application>();
        }
    }

    public class Application
    {
        private readonly ILogger<Application> logger;

        public Application(ILogger<Application> logger)
        {
            this.logger = logger;
            this.logger.LogInformation("In Application::ctor");
        }

        public async Task Run()
        {
            logger.LogInformation("Info: In Application::Run");
            logger.LogWarning("Warn: In Application::Run");
            logger.LogError("Error: In Application::Run");
            logger.LogCritical("Critical: In Application::Run");
        }

        //public void Run()
        //{
        //    logger.LogInformation("Info: In Application::Run");
        //    logger.LogWarning("Warn: In Application::Run");
        //    logger.LogError("Error: In Application::Run");
        //    logger.LogCritical("Critical: In Application::Run");
        //}
    }


来源:https://stackoverflow.com/questions/59575156/logging-to-console-with-di-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!