Search code examples
c#asp.netilogger

ILogger instance does not log in async method, but Console.WriteLine does


I have a class TCPTransport:

private ILogger _logger;

public TcpTransport(ILogger logger) {
    _logger = logger;
    _logger.LogDebug($"Init");
    OnTick += DoTick;
}

public async void MainLoop() {
    Console.WriteLine("Mainloop1");
    _logger.LogDebug($"Mainloop2");
    ....
}

When running this class, and calling the MainLoop method, I get the ILogger output "Init", and the Console output of "Mainloop1", yet Mainloop2 does not output at all.

I've tried to put it in a Task, and to make the thread sleep. I can't find any info on why this would happen, I assume it has to do with the fact that the method is async.


Solution

  • Console.Writeline and _logger.LogDebug maybe writing to different log levels. Try changing LogDebug with LogInformation.

    If you didn't edit the log level yourself, you can check appsettings.json file for the configured logging settings.