Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to get Azure WebJobs logging to Application Insights

5.00/5 (1 vote)
27 Sep 2023CPOL 6.2K  
Details the additional steps needed to get WebJobs logging to Application Insights.

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).

C#
  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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)