在C#中使用DI登录到控制台 [英] Logging to Console with DI in C#

查看:83
本文介绍了在C#中使用DI登录到控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只将.AddConsole()保留在ConfigureServices中,则无论LogLevel是什么,都不会记录到控制台,但是如果我添加.AddConsole().AddDebug(),则所有消息都会记录到控制台3次!我想念什么?谢谢!

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");
        }
    }
}

这是每个Log *()调用显示的内容:

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

更新/解决方案 感谢@panoskarajohn解决这个问题. App.Run()必须是异步的: 更改app.Run(); => Task.Run(() => app.Run()).Wait(); public void Run() => public async Task Run() 并且应该在没有debug()选项的情况下工作 我找不到发生这种情况的任何原因

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

有人知道为什么吗?

推荐答案

我不知道为什么addDebug()选项没有发生这种情况.

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

我想AddDebug()具有一些特殊的配置,并在程序退出之前刷新输出. 如果有任何启发请给我们.

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

控制台日志记录正在后台线程上进行.因此,如果应用程序退出得太快,则记录器没有时间记录-> https://github.com/aspnet/Logging/issues/631

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.

为了在您的代码中解决此问题.在程序末尾添加Console.Read(),以免退出.

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
        }

我还遇到了另一个解决方案,它是创建一个异步Task并等待它.

像这样更新代码.

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");
        }

最终结果应如下所示.

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");
        //}
    }

这篇关于在C#中使用DI登录到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆