I'm using Azure Functions 6 (.NET 6, isolated), with Application Insights enabled.
From different versions of Visual Studio, Azure Functions Core Tools, the default Microsoft templates and other docs showed a variety of ways to obtain ILogger
. I've seen:
ILoggerFactory
(from a default MS template):private readonly ILogger _logger;
public MyFunction(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<MyFunction>();
}
FunctionContext
(also from default MS template):public async Task<HttpResponseData> Run([HttpTrigger(...)] HttpRequestData req, FunctionContext executionContext)
{
var logger = executionContext.GetLogger("MyFunction);
}
ILogger
directly into the Run
method:public static void Run(EventGridEvent eventGridEvent, ICollector<string> outputSbMsg, ILogger logger)
ILogger<T>
:private readonly ILogger<MyFunction> _logger;
public MyFunction(ILogger<MyFunction> logger)
{
_logger = logger;
}
What are the differences of all these methods and which ones are the best to use?
ILogger<T>
:private readonly ILogger<MyFunction> _logger;
public MyFunction(ILogger<MyFunction> logger)
{
_logger = logger;
}
ILogger
directly into the Run
method:public static void Run(EventGridEvent eventGridEvent, ICollector<string> outputSbMsg, ILogger logger)
In this way, we can access the logger inside the specific Run method. outer Run it is not able to access.
FunctionContext
(also from default MS template):public async Task<HttpResponseData> Run([HttpTrigger(...)] HttpRequestData req, FunctionContext executionContext)
{
var logger = executionContext.GetLogger("MyFunction);
}
Which is similar to the 3rd point. But the difference between 2nd and 3rd was using Execution context. The Execution context contains the function information so we can get the details of the functions in an Execution context.
ILoggerFactory
(from a default MS template):private readonly ILogger _logger;
public MyFunction(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<MyFunction>();
}
Here ILoggerFactory
is brings together all the collections of ILoggerProvider
s, and the ILoggerFactory
creates ILogger<T>
instances for the application. It contains ILogger
, ILogger<T>
, ILoggerProvider
and ILoggerFactory
. so using this we can use the all usages of ILogger.
Either you can use the 1st or 4th approach which is the effective way to use ILogging.