微软扩展框架将自定义维度添加到记录器中,而不是每次调用?

问题描述 投票:0回答:1

我有一个azure函数。

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" } };

如你所见,我通过向BeginScope提供一个字典(属性)来添加自定义属性。有没有办法将字典添加到记录器中,这样我就不必为每次调用提供字典?记录器写到Application Insigths。

azure-application-insights azure-function-app microsoft-extensions-logging
1个回答
0
投票

要添加自定义尺寸,你可以使用 ITelemetryInitializer 为您的 azure 函数。

编写完自己的ITelemetryInitializer后,你需要在azure函数中注册它。请参考下面的示例代码。

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>();
        }
    }
}

测试结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.