So why would you ever log to Application Insights AND File log at the same time? Well, if you are hosting your own applications on your own machine, it can be great to have a file version of what’s happened. The file will be updated immediately, whereas Application Insights are sometimes up to 5 minutes behind.
Also, it gives you the opportunity to log at different levels. Application Insights is not cheap, so having Application Insights log only warnings and errors, but the file logging debug can be a money saver.
And, when developing, the file log is far superior to Application Insights.
STEP 1: THE NUGET PACKAGES
You need the following packages:
STEP 2: THE CONFIGURATION
This will configure the logging:
"ApplicationInsights": {
"InstrumentationKey": "[The instrumentation key]"
},
"Logging": {
"PathFormat": "[The path and file format used in file logging, e.g.: c:\\log-{Date}.txt]",
"LogLevel": {
"Default": "Information"
},
"ApplicationInsightsLoggerProvider": {
"LogLevel": {
"Default": "Warning"
}
}
}
The “Logging” section configures the different log levels for file and Application Insights.
STEP 3: THE EXTENSION METHOD
This method allows you to add logging easily:
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
namespace MyCode
{
public static class WebApplicationBuilderExtensions
{
public static void AddLogging(this WebApplicationBuilder builder)
{
// Add file logging
builder.Host.ConfigureLogging(logging =>
{
logging.AddFile(builder.Configuration.GetSection("Logging"));
}
);
// Add Application Insights Logging
var options = new ApplicationInsightsServiceOptions();
options.InstrumentationKey = builder.Configuration["ApplicationInsights:InstrumentationKey"];
builder.Services.AddApplicationInsightsTelemetry(options);
}
}
}
STEP 4: CALL THE METHOD WHEN BUILDING YOUR APPLICATION
This is an example where I configure my logging:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
var webApplicationOptions = new WebApplicationOptions();
var builder = WebApplication.CreateBuilder(webApplicationOptions);
builder.AddLogging();
...
...
...
builder.Build();