azure-functions-dotnet-worker: Logging using an `ILogger` instance does not work when it is not part of a function execution
Logging using a constructor injected ILogger<T> instance does not work when it is not part of a function execution. This means logging does not work inside an implementation of IHostedService or BackgroundService which is registered as a hosted service in worker.
internal class CacheRefreshService : BackgroundService
{
private readonly ILogger<CacheRefreshService> _logger;
public CacheRefreshService(ILogger<CacheRefreshService> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Below logging does not work.
_logger.LogInformation("Inside ExecuteAsync");
// code to refresh cache.
await Task.Delay(5000);
}
}
In this case, the code executed in the background service has no invocation id associated with it. So I believe this line in host is dropping the log messages sent from worker to host.
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Comments: 15 (11 by maintainers)
@ayrton97, my question is based on understanding how Functions operate. Take a consumption plan where a Function is constrained in the execution time. That means b/g service or not, the function will be shut down and the background service won’t be able to run.
That’s not how Functions work, though. Functions require a trigger. Timer, queue, something that would trigger it. And if the b/g service will resume within the maximum allotted time as a result of an invocation, I can see it working. But if it requires more time or there’s no trigger, how will that work, @ayrton97?
@kshyju I might be missing some context/knowledge here, but a function has to be triggered. And a
BackgroundServicewould not be executed if there’s no trigger.