简体   繁体   English

登录.Net核心控制台应用程序不起作用

[英]Logging in .Net core console application not working

I am following this tutorial: https://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/我正在关注本教程: https ://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/

and accordingly installed the packages but log is not getting printed anywhere.并相应地安装了软件包,但日志没有在任何地方打印。

This is my code:这是我的代码:

  var serviceProvider = new ServiceCollection()
            .AddLogging()
            .AddTransient<IFoo, Foo>(s =>
            {
                return new Foo()})
            .BuildServiceProvider();

            //configure console logging
            serviceProvider
                .GetService<ILoggerFactory>()
                .AddConsole(LogLevel.Debug);

 var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Program>();

            logger.LogError("Starting application");

Turns out the console logging provider doesn't immediately flush the messages to the console like it did in the net-core-1.x versions.事实证明,控制台日志记录提供程序不会像在 net-core-1.x 版本中那样立即将消息刷新到控制台。 It appears to run on a different thread.它似乎在不同的线程上运行。 See this web page for info: https://github.com/aspnet/Logging/issues/631有关信息,请参阅此网页: https ://github.com/aspnet/Logging/issues/631

You can add at the end of the Main function.您可以在Main函数的末尾添加。

serviceProvider.Dispose();

or you can add .AddDebug()或者你可以添加.AddDebug()

            serviceProvider
            .GetService<ILoggerFactory>()
            .AddConsole(LogLevel.Debug)
            .AddDebug();

Creating a new ServiceProvider and HostBuilder may not be worth it if we just want a Logging in Console Application because it's a bit of extra caution to clean it up or dispose of.如果我们只想在控制台应用程序中登录,那么创建一个新的 ServiceProvider 和 HostBuilder 可能不值得,因为清理或处理它需要格外小心。 Rather, I would suggest just have Logging Factory to use logger and that will solve the logging if that is only what we want.相反,我建议让 Logging Factory 使用 logger,如果这只是我们想要的,那将解决日志记录。

public static class ApplicationLogging
{
    public static ILoggerFactory LogFactory { get; } = LoggerFactory.Create(builder =>
        builder.ClearProviders(); 
        // Clear Microsoft's default providers (like eventlogs and others)
        builder.AddSimpleConsole(options =>
        {
            options.IncludeScopes = true;
            options.SingleLine = true;
            options.TimestampFormat = "hh:mm:ss ";
        });
        builder.AddApplicationInsights("instrument-key");
    });
    public static ILogger<T> CreateLogger<T>() => LogFactory.CreateLogger<T>();
}

static void Main(string[] args)
{
    var logger = ApplicationLogging.CreateLogger<Program>();
    logger.LogInformation("Let's do some work");
    logger.LogWarning("I am going Crazy now!!!");
    logger.LogInformation("Seems like we are finished our work!");
    Console.ReadLine();
}

I landed on this thread trying to troubleshoot why console logging didn't work and this answer documents what I found.我登陆这个线程试图解决控制台日志记录不起作用的原因,这个答案记录了我发现的内容。 Packages used: Microsoft.Extensions.Logging Microsoft.Extensions.Logging.Console Microsoft.Extensions.Logging.Debug使用的包:Microsoft.Extensions.Logging Microsoft.Extensions.Logging.Console Microsoft.Extensions.Logging.Debug

Application: .NET Core 2.2 Console (Microsoft.NET.Sdk, netcoreapp2.2) Using Microsoft.Extensions.Hosting.IHost, this is how I added console logging:应用程序:.NET Core 2.2 Console (Microsoft.NET.Sdk, netcoreapp2.2) 使用 Microsoft.Extensions.Hosting.IHost,这是我添加控制台日志的方式:

var hostBuilder = new HostBuilder()
                // Other Configuration omitted for brevity
                .ConfigureLogging((hostBuilderContext, loggingBuilder) =>
                {
                    loggingBuilder.AddConfiguration(hostBuilderContext.Configuration.GetSection("Logging"));
                    loggingBuilder.AddConsole(options =>
                    {
                        options.IncludeScopes = true;
                    });
                    loggingBuilder.AddDebug();
                });
// Start the application
await hostBuilder.RunConsoleAsync();

Interestingly, if I remove the options parameter in the call to AddConsole, I do not see any logging.有趣的是,如果我在调用 AddConsole 时删除 options 参数,我看不到任何日志记录。 I believe this is so because I use an ILogger in my code that emits log statements:我相信之所以如此,是因为我在代码中使用了 ILogger 来发出日志语句:

public class ClassThatLogs
{
    private readonly ILogger<ClassThatLogs> _logger;

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

    public void DoWork()
    {
        _logger.LogInformation("Working");
    }
}

If I publish the console app as:如果我将控制台应用程序发布为:

single file _log.LogDebug provide no output单个文件 _log.LogDebug 不提供输出

when I publish it as not a single file (so I only uncheck the single file option) _log.LogDebug provides outputs on the console all my debugging statements.当我将它作为不是单个文件发布时(所以我只取消选中单个文件选项)_log.LogDebug 在控制台上提供我所有调试语句的输出。 No other changes than unchecking single file.除了取消选中单个文件外,没有其他更改。

So by only unticking "produce single file" my _logging.LogDebug starts to write stuff to the console.因此,只需取消勾选“生成单个文件”,我的 _logging.LogDebug 就会开始将内容写入控制台。

在此处输入图像描述

Seems to be this: https://github.com/serilog/serilog-settings-configuration/issues/244似乎是这样的: https ://github.com/serilog/serilog-settings-configuration/issues/244

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM