0

I just moved from .net core 2 to .net core 3.1 We am facing issues finding the appropriate way to writing and using Nlog in my startup.cs file.

I have my program file as:

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

In .net core 2.0 we were passing in constructor as:

 private readonly ILogger<Startup> _logger;
 public Startup(IWebHostEnvironment env, ILogger<Startup> logger)
 {
    _logger = logger;
 }

And then in my ConfigureServices and Configure method I was using this logger to write logs. But with .net core 3 this has been changed. Now I am planning to use Nlog but I am not sure how can I write logs with Nlog in my startup file. Any inputs please.

Brenda
  • 510
  • 3
  • 13
  • 36
  • 1
    Logging in `ConfigureServices` is not officially supported, but many start up tasks can be moved into service classes. For example you can implement `IConfigureOptions` to configure anything that follows the options pattern, which includes all microsoft services. – Jeremy Lakeman Sep 22 '20 at 01:40
  • You can also get more hints in the answers to [this question](https://stackoverflow.com/questions/41287648/how-do-i-write-logs-from-within-startup-cs) – eduherminio Sep 23 '20 at 01:24

0 Answers0