【问题标题】:Logging within Program.cs在 Program.cs 中记录
【发布时间】:2017-07-20 16:59:47
【问题描述】:

是否可以在 Program.cs Main 方法中获取 ILogger?我想将它传递给在该方法中创建的服务。

我只在 SO How do I write logs from within Startup.cs 上找到了这个,但这是在 Startup.cs 中记录的。

【问题讨论】:

    标签: logging asp.net-core .net-core asp.net-core-mvc


    【解决方案1】:

    在谷歌搜索后偶然发现了答案。

    using System;
    using Microsoft.Extensions.Logging;
    
    namespace ConsoleApplication
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var logFactory = new LoggerFactory()
                .AddConsole(LogLevel.Debug)
                .AddDebug();
    
                var logger = logFactory.CreateLogger<Type>();
    
                logger.LogInformation("this is debug log");
            }
        }
    }
    

    https://askguanyu.wordpress.com/2016/09/26/net-core-101-e06-net-core-logging/致敬

    【讨论】:

    • 您应该看看this,这样您就可以在应用程序的其余部分使用相同的记录器实例。
    • @anserk 不要认为这是可能的,因为 ILogger 实例是通用类型的(即ILogger&lt;Startup&gt;)。
    • 这不再适用于 .NET Core 3.1 及更高版本。
    【解决方案2】:

    这就是我设法让Startup.cs(在我的例子中是Log4Net)中配置的ILogger接口在Program.cs内部工作的方法:

    public static void Main(string[] args)
    {
        var host = BuildWebHost(args);
    
        ILogger logger = host.Services.GetService<ILogger<Program>>();
    
        try
        {
            logger.LogInformation("Starting web host");
    
            host.Run();
        }
        catch (Exception ex)
        {
            logger.LogCritical(ex, "Starting web host failed.");
        }
    }
    
    • 添加using Microsoft.Extensions.DependencyInjection; 以便GetService 中的泛型类型按预期工作。

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2019-11-19
      • 1970-01-01
      相关资源
      最近更新 更多