Introduction
With regular App Services, if you enabled Application Insights, your ILogger logs will get written into Application Insights without having to do anything special. This is not the case with WebJobs though. After wasting a few hours trying to figure out why my logs were not showing up, here’s a solution I found that worked.
Step 1
Install the latest version of Microsoft.Azure.WebJobs.Logging.ApplicationInsights.
Step 2
Modify your startup code as follows (lines 12 to 17).
1 public static void Main(string[] args)
2 {
3 IHost host = Host.CreateDefaultBuilder(args)
4 .ConfigureServices(services =>
5 {
6 services.AddHostedService<Worker>();
7 })
8 .ConfigureLogging((context, builder) =>
9 {
10 builder.AddConsole();
11
12 var key = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
13 if (!string.IsNullOrEmpty(key))
14 {
15 builder.AddApplicationInsightsWebJobs(
16 options => options.InstrumentationKey = key);
17 }
18 })
19 .Build();
20
21 host.Run();
22 }
And that’s it. Remember that there’s usually a 1-2 minute delay before your logs show up in App Insights, and it could be as high as 3-4 minutes if it’s the first time you deploy. So, don’t panic if you don’t see the logs right away. Happy debugging!
References