Application Insights Logging in Azure Functions
By Harry Bellamy
- 2 minutes read - 249 wordsIf you’re writing Azure Functions you’re probably familiar with Application Insights for doing logging. The basic examples that Microsoft supply log to Application Insights out of the box.
What these examples don’t fully explain, however, is how to log in a class that isn’t the main (i.e. top-level) function class.
A Basic Setup
Let’s consider a basic setup, where the function logic is all contained in a single class, away from the main function.
using Microsoft.Extensions.Logging;
namespace AzureFunction.Example.Implementation
{
public class DoStuff
{
private readonly ILogger<DoStuff> logger;
public DoStuff(ILogger<DoStuff> logger)
{
this.logger = logger;
}
public void DoIt()
{
logger.LogInformation("Starting to do it.");
// Do something
// ...
logger.LogInformation("Done now.");
}
}
}
Note that ILogger<T>
is being injected here. This is setup in the default dependency injection configuration, so there’s no need to add it manually.
Unfortunately this isn’t sufficient for the logging to appear in Application Insights - some further configuration changes are required.
The host.json
will need to be changed as well:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
},
"logLevel": {
"AzureFunction.Example": "Information"
}
}
}
Here we’ve added the logLevel
section.
The namespace specified as a child of logLevel
is AzureFunction.Example
- this namespace and all its children will have the specified log level applied to their loggers.
Assuming all your classes are in the defined namespace (or a child namespace), this change you will allow you to log in any and all classes of your solution!