Jononline

Logging
Application insights

Adding Application Insights logging to a WebJob

Package: Microsoft.Azure.WebJobs.Logging.ApplicationInsights

                    
using Microsoft.Extensions.Hosting; 
using Microsoft.Extensions.Logging; 

class Program 
{ 
    static async Task Main() 
    { 
        var builder = new HostBuilder(); 

        builder.ConfigureWebJobs(b => 
        { 
            b.AddTimers(); 
        });

        builder.ConfigureLogging((context, b) => 
        { 
            b.SetMinimumLevel(LogLevel.Error); 
            b.AddFilter("Function", LogLevel.Information); 
            b.AddFilter("Host", LogLevel.Debug); 
            b.AddConsole(); 

            string? instrumentationKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]; 

            if(!string.IsNullOrEmpty(instrumentationKey)) 
            { 
                b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = instrumentationKey); 
            } 
        }); 

        var host = builder.Build(); 
        using (host) 
        { 
            await host.RunAsync(); 
        } 
    } 
} 
                    
                    

Adding Application Insights OpenTelemetry logging to an api

Package: Azure.Monitor.OpenTelemetry.AspNetCore

Program.cs

                    
using Azure.Monitor.OpenTelemetry.AspNetCore; 

...

// Logging
builder.Services.AddOpenTelemetry().UseAzureMonitor();

var app = builder.Build(); 

...
                    
                    
ILogger<class> will work as usual

Adding Application Insights OpenTelemetry logging to a webjob

Package: Azure.Monitor.OpenTelemetry.AspNetCore

Program.cs

This includes an optional method of using Managed Identity to authenticate with Application Insights. In this case, no connection string is needed, but it can help to ensure the correct resource is used
                    
 using Azure.Identity;
 using Azure.Monitor.OpenTelemetry.AspNetCore;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Hosting;
                      
class Program
{
    static async Task Main()
    {
        var builder = new HostBuilder();
                        
        builder.ConfigureWebJobs(b =>
        {
            b.AddTimers();
        });
                        
        builder.ConfigureServices((hostContext, services) =>
        {
            services.AddOpenTelemetry()
            .UseAzureMonitor(options =>
            {
                options.Credential = new DefaultAzureCredential();
            });
        });
                        
        var host = builder.Build();
        using (host)
        {
            await host.RunAsync();
        }
    }
}
                    
                    
ILogger<class> will work as usual