Tuesday, June 24, 2025

Azure WebJob with Timer Trigger and Application Insights Logging in .NET 8

 Azure WebJob with Timer Trigger and Application Insights Logging in .NET 8

// dotnet add package Microsoft.Azure.WebJobs.Extensions
// dotnet add package Microsoft.Azure.WebJobs.Extensions.Timers
// dotnet add package Microsoft.Extensions.Hosting
// dotnet add package Microsoft.Extensions.Logging.ApplicationInsights

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.ApplicationInsights.Extensibility;

var host = new HostBuilder()
    .ConfigureWebJobs(b =>
    {
        b.AddTimers();
    })
    .ConfigureLogging((context, b) =>
    {
        b.AddConsole();
        // Add Application Insights logging
        b.AddApplicationInsights(
            configureTelemetryConfiguration: (config) =>
            {
                // Optionally configure Telemetry here
            },
            configureApplicationInsightsLoggerOptions: (options) => { }
        );
    })
    .ConfigureServices((context, services) =>
    {
        services.AddSingleton<MyFunctions>();
        // Set Application Insights connection string or instrumentation key
        services.Configure<TelemetryConfiguration>((config) =>
        {
            //config.ConnectionString =
context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
            config.ConnectionString =
"InstrumentationKey=5f3e190f-999a-46f6-aea1-ddc46b8a9de9;IngestionEndpoint=
https://westus2-4.in.applicationinsights.azure.com/;
LiveEndpoint=https://westus2.livediagnostics.monitor.azure.com";
            // "InstrumentationKey=5f3e190f-999a-46f6-aea1-ddc46b8a9de9;
IngestionEndpoint=https://westus2-4.in.applicationinsights.azure.com/;
LiveEndpoint=https://westus2.livediagnostics.monitor.azure.com;
ApplicationId=528f3612-f614-4768-a707-1aeb6d61c551
        });
    })
    .Build();

host.Run();

public class MyFunctions
{
    private readonly ILogger<MyFunctions> _logger;

    public MyFunctions(ILogger<MyFunctions> logger)
    {
        _logger = logger;
    }

    public void ProcessTimer([TimerTrigger("0 */1 * * * *")] TimerInfo timerInfo)
    {
        _logger.LogInformation($"WebJob executed at: {DateTime.Now}");
    }
}

output:



No comments:

Post a Comment

Featured Post

Azure WebJob with Timer Trigger and Application Insights Logging in .NET 8

 Azure WebJob with Timer Trigger and Application Insights Logging in .NET 8 // dotnet add package Microsoft.Azure.WebJobs.Extensions // dotn...

Popular posts