首页 > 解决方案 > 使用 LoggerFactory 输出到控制台;.AddConsole() 的问题

问题描述

我正在尝试了解和实现 ac# winforms 应用程序中的日志记录。在大多数/所有示例和文档中,我发现他们使用.AddConsole()了以下错误:

“ILoggingBuilder”不包含 AddConsole 的定义,也没有可访问的扩展方法“Add Console”...

我当前的代码如下:

using Microsoft.Extensions.DependencyInjection; //<-----was suggested in an example but does nothing--<<<<
using Microsoft.Extensions.Logging;

    public partial class FormMain : Form
    {
        public FormMain()
        {
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder
                    .AddFilter("Microsoft", LogLevel.Warning)
                    .AddFilter("System", LogLevel.Warning)
                    .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
                    .AddConsole() //<-----------------------line with error---------<<<<
                    .AddEventLog();
            });

            ILogger logger = loggerFactory.CreateLogger<FormMain>();
            logger.LogInformation("Example log message");

            InitializeComponent();

            ...rest of program follows...

您能否协助指出如何编译示例代码?

如果您有指向我可以关注的教程/文档的链接,我也将不胜感激。

我在 Microsoft Docs 中看到有一个 ILoggerFactory.AddProvider(ILoggerProvider) 方法,但我也没有成功。

感谢您的时间。

标签: c#winformslogging

解决方案


There are various different logging mechanisms and you don't get them out of the box. You are missing the appropriate nuget package. You need to add a package reference to Microsoft.Extensions.Logging.Console. Once you do that, the extension methods should be available to you.

You can find the package on nuget.org.


推荐阅读