简体   繁体   English

如何使 .net 核心 3.1 控制台应用程序中的控制台记录器工作

[英]How to make console logger in .net core 3.1 console app work

I'm building a.Net Core 3.1 console app and I want to use the build in console logging.我正在构建一个.Net Core 3.1 控制台应用程序,我想在控制台日志记录中使用构建。 There are a zillion articles on .net logging, but I have not been able to find a sample that actually does write in the console.关于 .net 日志记录的文章数不胜数,但我无法找到实际在控制台中写入的示例。

   namespace test
   {
      class Program
      {

        static void Main(string[] args)
        {
            var serviceProvider = new ServiceCollection()
                .AddLogging(config => config.ClearProviders().AddConsole().SetMinimumLevel(LogLevel.Trace))
                .BuildServiceProvider();

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


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

            logger.LogDebug("All done!");

            Console.Write("Yup");
        }
    }

It compiles and runs, and even writes "Yup" to the console, but the "All done."它编译并运行,甚至将“Yup”写入控制台,但“All done”。 is not shown: Output in console window:未显示:控制台窗口中的 Output: 控制台输出

This is my sample project structure:这是我的示例项目结构: 在此处输入图像描述

What am I missing?我错过了什么?

It was a dispose of Services: Fix thanks to Jeremy Lakeman:这是对服务的处置:感谢杰里米·莱克曼(Jeremy Lakeman):

            static void Main(string[] args)
        {
            using (var serviceProvider = new ServiceCollection()
                .AddLogging(config => config.ClearProviders().AddConsole().SetMinimumLevel(LogLevel.Trace))
                .BuildServiceProvider())
            {
                //configure console logging
                serviceProvider
                    .GetService<ILoggerFactory>();


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

                // run app logic

                logger.LogDebug("All done!");
            }

            Console.Write("Yup");
        }

So that logging doesn't adversely impact the performance of your program, it may be written asynchronously.因此,日志记录不会对程序的性能产生不利影响,它可以异步编写。

Disposing the log provider and other logging classes should cause the log to flush.处理日志提供程序和其他日志记录类应该会导致日志刷新。

The service provider should also dispose all services when it is disposed.服务提供者还应在处置时处置所有服务。

I might be late but worth adding some inputs in case it helps.我可能会迟到,但值得添加一些输入以防万一。 I was also struggling with this logging in .net core and keep having breaking changes with the latest release.我还在 .net 内核中苦苦挣扎,并在最新版本中不断进行重大更改。 However, can't complain as it keeps getting better and better.但是,不能抱怨,因为它越来越好。 Here is what I have done with the .net core 5 released.这是我对发布的 .net 内核 5 所做的事情。

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 ";
            }).SetMinimumLevel(LogLevel.Warning);
    });

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

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

相关问题 Create.Net Core 3.1 控制台应用程序到 Debian 9,它应该可以工作吗? - Create .Net Core 3.1 console app to Debian 9, should it just work? 如何正确地为在 systemd 上运行的 Ubuntu 制作无尽的控制台应用程序 .NET Core 3.1 - How to make correctly endless console app .NET Core 3.1 for Ubuntu running on systemd .NET Core 3.1 控制台应用作为 Windows 服务 - .NET Core 3.1 Console App as a Windows Service .NET Core 3.1 控制台应用程序无法在 Windows 上运行 7 - .NET Core 3.1 Console App will not run on Windows 7 在 .net core 3.1 控制台应用程序中将 nlog 与 ApplicationInsightsTelemetryWorkerService 一起使用 - Using nlog with ApplicationInsightsTelemetryWorkerService in .net core 3.1 console app 通过web浏览器在.Net core 3.1中公开控制台应用程序信息 - Expose console app info through web browser in .Net core 3.1 使 .net 核心控制台应用程序成为单个 .exe - Make .net core console app a single .exe 如何从 VS2019 中的 .NET Core 3.1 控制台应用程序连接到 Azure 文件存储 - How to connect to a Azure File Store from a .NET Core 3.1 console app in VS2019 如何在 c# .net core 3.1 控制台应用程序中保存设置? - how to save settings in c# .net core 3.1 console application? 如何在带有 .Net3.1 的 C# 控制台应用程序中使用 docker 创建 serilog 记录器文件 - How to create a serilog logger file using docker in C# console Application with .Net3.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM