How do I write logs from within Startup.cs?

前端 未结 10 1412
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 04:16

In order to debug a .NET Core app which is failing on startup, I would like to write logs from within the startup.cs file. I have logging setup within the file that can be u

10条回答
  •  生来不讨喜
    2020-12-01 04:28

    None of the existing answers worked for me. I'm using NLog, and even building a new ServiceCollection, calling .CreateBuilder() on any service collection, creating a logging service ... none of that would write to a log file during ConfigureServices.

    The problem is that logging isn't really a thing until after the ServiceCollection is built, and it's not built during ConfigureServices.

    Basically, I just want (need) to log what's going on during startup in a configuration extension method, because the only tier I'm having a problem on is PROD, where I can't attach a debugger.

    The solution that worked for me was using the old .NET Framework NLog method:

    private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
    

    Added that right to the extension method class, and I was able to write to a log ("the" log) during ConfigureServices and after.

    I have no idea if this is a good idea to actually release into production code (I don't know if the .NET controlled ILogger and this NLog.ILogger will conflict at any point), but I only needed it to see what was going on.

提交回复
热议问题