gpt4 book ai didi

azure - 如何在 Azure Function 中使用 TelemetryConfiguration 的依赖项注入(inject)

转载 作者:行者123 更新时间:2023-12-03 15:13:30 27 4
gpt4 key购买 nike

我尝试在 Azure Functions 中使用依赖项注入(inject)进行 TelemetryConfiguration。在我的函数中,当我在函数构造函数中注入(inject) TelemetryConfiguration 时,我将解决它。我想我不太明白如何在 StartUp 中使用 TelemetryConfiguration,这就是为什么我收到异常。如何添加我已经配置的 TelemetryConfiguration。

我在这里做了一个简单的例子,说明了我到目前为止所做的事情。

[assembly: FunctionsStartup(typeof(StartUp))]
public class StartUp : FunctionsStartup
{
private string OmsModule { get; } = "OMS.VA";

public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.Configure<TelemetryConfiguration>(
(o) =>
{
o.InstrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
o.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
});
}
}

public class StopPlaceUpdateTimerTrigger
{
private TelemetryClient _telemetryClient;
private string _azureWebJobsStorage;

public StopPlaceUpdateTimerTrigger(TelemetryConfiguration telemetryConfiguration)
{
_telemetryClient = new TelemetryClient(telemetryConfiguration);
}

[FunctionName("StopPlaceLoader")]
public async Task StopPlaceLoaderMain([TimerTrigger("%CRON_EXPRESSION%", RunOnStartup = true)]TimerInfo myTimerInfo, ILogger log, ExecutionContext context)
{
SetConfig(context);
var cloudTable = await GetCloudTableAsync();
if (cloudTable == null)
{
//Do nothing
}
//Do nothing
}

private async Task<CloudTable> GetCloudTableAsync()
{
var storageAccount = CloudStorageAccount.Parse(_azureWebJobsStorage);
var tableClient = storageAccount.CreateCloudTableClient();
var table = tableClient.GetTableReference(nameof(StopPlaceLoaderCacheRecord));

if (!await table.ExistsAsync())
{
await table.CreateIfNotExistsAsync();
}
return table;
}

private void SetConfig(ExecutionContext context)
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true)
.AddEnvironmentVariables()
.Build();
_azureWebJobsStorage = config["AzureWebJobsStorage"];
}
}


//local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol...",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"EnableMSDeployAppOffline": "True",
"CRON_EXPRESSION": "0 */5 22-3 * * *",
"APPINSIGHTS_INSTRUMENTATIONKEY": "..."
}
}

我收到以下异常;Microsoft.Extensions.DependencyInjection.Abstractions:尝试激活“OMS.VA.RealTime.StopPlaceLoader.StopPlaceUpdateTimerTrigger”时无法解析类型“Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration”的服务。

最佳答案

更新:

我们可以将这行代码 var newConfig = TelemetryConfiguration.Active; 更改为 var newConfig = TelemetryConfiguration.CreateDefault(); ,因为 TelemetryConfiguration.Active 已弃用。

<小时/>

请使用以下代码作为 TelemetryConfiguration DI,我使用 blob 触发函数对其进行了测试,效果良好:

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

[assembly: WebJobsStartup(typeof(FunctionApp17.MyStartup))]
namespace FunctionApp17
{

public class MyStartup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
var configDescriptor = builder.Services.SingleOrDefault(tc => tc.ServiceType == typeof(TelemetryConfiguration));
if (configDescriptor?.ImplementationFactory != null)
{
var implFactory = configDescriptor.ImplementationFactory;
builder.Services.Remove(configDescriptor);
builder.Services.AddSingleton(provider =>
{
if (implFactory.Invoke(provider) is TelemetryConfiguration config)
{
var newConfig = TelemetryConfiguration.Active;
newConfig.ApplicationIdProvider = config.ApplicationIdProvider;
newConfig.InstrumentationKey = config.InstrumentationKey;

return newConfig;
}
return null;
});
}
}
}

public class Function1
{
private TelemetryClient _telemetryClient;

public Function1(TelemetryConfiguration telemetryConfiguration)
{
_telemetryClient = new TelemetryClient(telemetryConfiguration);
}

[FunctionName("Function1")]
public void Run([BlobTrigger("samples-workitems/{name}", Connection = "AzureWebJobsStorage")]Stream myBlob, string name, ILogger log)
{
log.LogInformation($"!!!!!!!!!! C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
_telemetryClient.TrackTrace("this is a test message from DI of telemetry client !!!!!!!!!!!!!!");
}
}
}

测试结果如下,我可以在azure门户的application Insights中看到日志:

enter image description here

还有一件事,我看到您尝试在代码中使用 ITelemetry Initializer。您可以关注这个GitHub issue用于您的ITelemetry InitializerItelemetry Processor

关于azure - 如何在 Azure Function 中使用 TelemetryConfiguration 的依赖项注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397520/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com