Search code examples
azure-application-insightsazure-function-appmicrosoft-extensions-logging

Microsoft Extension Framework add custom dimensions to the logger instead of each call?


I have an azure function:

public void Run([TimerTrigger("0 0 0 * * *", RunOnStartup =true)]TimerInfo myTimer, ILogger log)
{
     using (logger.BeginScope(properties))
     {
        logger.LogTrace(message);
     }           
}

Dictionary<string, object> _props = new Dictionary<string, object> { { "service", "exchange.rates.procces" } };

As you can see I add custom properties by providing a dictionary (properties) to BeginScope. Is there anyway to add the dictionary to the logger, so I do not have to provide the dictionary for each call? The logger write to Application Insigths.


Solution

  • To add custom dimensions, you can take use of ITelemetryInitializer for your azure function.

    After writing your own ITelemetryInitializer, you need to register it in azure function. Please refer to the sample code below:

    using Microsoft.ApplicationInsights.Channel;
    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Hosting;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using System;
    
    //add thie line of code before namespace
    [assembly: WebJobsStartup(typeof(FunctionApp2.MyStartup))]
    namespace FunctionApp2
    {
        public class Function1
        {
    
            [FunctionName("Function1")]
            public void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log)
            {            
                log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
                log.LogInformation("333 this is a test message...");
            }
        }
    
        //define your custom ITelemetryInitializer which is used to add custom dimension
        internal class MyTelemetryInitializer : ITelemetryInitializer
        {
            public void Initialize(ITelemetry telemetry)
            {
                if (telemetry != null && !telemetry.Context.GlobalProperties.ContainsKey("my_custom_dimen22"))
                {
                    telemetry.Context.GlobalProperties.Add("my_custom_dimen22", "Hello, this is custom dimension for request!!!");
                }
            }
        }
    
        //register your custom ITelemetryInitializer
        public class MyStartup : IWebJobsStartup
        {
            public void Configure(IWebJobsBuilder builder)
            {
                builder.Services.AddSingleton<ITelemetryInitializer, MyTelemetryInitializer>();
            }
        }
    }
    

    The test result:

    enter image description here