C# .net Core 3.1使用Nlog在启动时写入日志

C# .net Core 3.1使用Nlog在启动时写入日志,c#,.net-core,nlog,C#,.net Core,Nlog,我刚从.NETCore2迁移到.NETCore3.1 我们面临着在我的startup.cs文件中找到编写和使用Nlog的适当方法的问题 我的程序文件为: public static void Main(string[] args) { // NLog: setup the logger first to catch all errors var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.c

我刚从.NETCore2迁移到.NETCore3.1 我们面临着在我的startup.cs文件中找到编写和使用Nlog的适当方法的问题

我的程序文件为:

public static void Main(string[] args)
    {
        // NLog: setup the logger first to catch all errors
        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config")
            .GetCurrentClassLogger();
        try
        {
            logger.Debug("init main");
        CreateWebHostBuilder(args)
            .Build()
            .Run();
    }
    catch (Exception ex)
    {
        //NLog: catch setup errors
        logger.Error(ex, "Stopped program because of exception");
        throw;
    }
    finally
    {
        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        NLog.LogManager.Shutdown();
    }
}

public static IHostBuilder CreateWebHostBuilder(string[] args) =>


 Host.CreateDefaultBuilder(args)
       .ConfigureWebHostDefaults(webBuilder =>
       {
           webBuilder.ConfigureKestrel(options =>
           {
               options.Limits.MaxRequestBodySize = null;
               options.Limits.KeepAliveTimeout = TimeSpan.MaxValue;
           });
           webBuilder.UseStartup<Startup>();
       })
        .ConfigureLogging(logging =>
       {
           logging.ClearProviders();
           logging.SetMinimumLevel(LogLevel.Trace);
       })
        .UseNLog();
publicstaticvoidmain(字符串[]args)
{
//NLog:首先设置记录器以捕获所有错误
var logger=NLog.Web.NLogBuilder.ConfigureNLog(“NLog.config”)
.GetCurrentClassLogger();
尝试
{
Debug(“init main”);
CreateWebHostBuilder(args)
.Build()
.Run();
}
捕获(例外情况除外)
{
//NLog:捕获设置错误
logger.Error(例如,“由于异常而停止程序”);
投掷;
}
最后
{
//确保在应用程序退出之前刷新并停止内部计时器/线程(避免Linux上的分段错误)
NLog.LogManager.Shutdown();
}
}
公共静态IHostBuilder CreateWebHostBuilder(字符串[]args)=>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder=>
{
webBuilder.ConfigureKestrel(选项=>
{
options.Limits.MaxRequestBodySize=null;
options.Limits.KeepAliveTimeout=TimeSpan.MaxValue;
});
webBuilder.UseStartup();
})
.ConfigureLogging(日志=>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog();
在.net core 2.0中,我们将构造函数传递为:

 private readonly ILogger<Startup> _logger;
 public Startup(IWebHostEnvironment env, ILogger<Startup> logger)
 {
    _logger = logger;
 }
专用只读ILogger\u记录器;
公共启动(IWebHostEnvironment环境、ILogger记录器)
{
_记录器=记录器;
}

然后在我的ConfigureServices和Configure方法中,我使用这个记录器来编写日志。但在.NETCore3中,这一点已经改变了。现在我计划使用Nlog,但我不确定如何在启动文件中使用Nlog编写日志。请输入任何信息。

官方不支持登录
ConfigureServices
,但许多启动任务可以移动到服务类中。例如,您可以实现
IConfigureOptions
来配置遵循选项模式的任何内容,其中包括所有microsoft服务。您还可以在的答案中获得更多提示