如何在隔离的 .NET 7 Azure 函数中获取 Application Insights TelemetryClient?

huangapple go评论69阅读模式
英文:

How to get Application Insights TelemetryClient in Isolated .NET 7 Azure function?

问题

I create an Azure Function from the newest Visual Studio template and deploy it to Azure. I have setup Application Insights in the Azure portal so the actual code doesn't yet know about AppInsights. So far everything works.

Now I want to log some custom telemetry. What do I need to do?

I've tried the following:

  • Taking a dependency on TelemetryClient
    • DI cannot resolve it
  • Taking a dependency on TelemetryConfiguration
    • DI cannot resolve it
  • Taking a dependency on IOptions<TelemetryConfiguration> and creating TelemetryClient from options.Value
    • Nothing happens. I guess just having the APPINSIGHTS_INSTRUMENTATIONKEY key in configuration is not enough

What to do?

英文:

I create an Azure Function from the newest Visual Studio template and deploy it to Azure. I have setup Application Insights in the Azure portal so the actual code doesn't yet know about AppInsights. So far everything works.

Now I want to log some custom telemetry. What do I need to do?

I've tried the following:

  • Taking a dependency on TelemetryClient
    • DI cannot resolve it
  • Taking a dependency on TelemetryConfiguration
    • DI cannot resolve it
  • Taking a dependency on IOptions&lt;TelemetryConfiguration&gt; and creating TelemetryClient from options.Value
    • Nothing happens. I guess just having the APPINSIGHTS_INSTRUMENTATIONKEY key in configuration is not enough

What to do?

答案1

得分: 2

以下是您要翻译的内容:

.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <OutputType>Exe</OutputType>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.WindowsServer" Version="2.21.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.21.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.10.0" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.7.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.35" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext" />
  </ItemGroup>
</Project>

local.settings.json:

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "APPINSIGHTS_INSTRUMENTATIONKEY": "308f2xxxxx039"
    }
}

Function.cs:

using System.Net;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Microsoft.ApplicationInsights.DataContracts;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace FunctionApp23
{
    public class Function1
    {
        public readonly TelemetryClient _tc;

        public Function1(TelemetryClient telClient)
        {
            _tc = telClient;
        }

        [Function("Function1")]
        public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, ILogger log)
        {
            _tc.TrackEvent("Function is running Rithwik");

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            response.WriteString("Welcome to Azure Functions!");

            _tc.TrackEvent("Function is Completed Rithwik");

            return response;
        }
    }
}

host.json:

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  }
}

Output:

如何在隔离的 .NET 7 Azure 函数中获取 Application Insights TelemetryClient?

如何在隔离的 .NET 7 Azure 函数中获取 Application Insights TelemetryClient?

然后在门户中:

如何在隔离的 .NET 7 Azure 函数中获取 Application Insights TelemetryClient?

如何在隔离的 .NET 7 Azure 函数中获取 Application Insights TelemetryClient?

尝试按照上述步骤在门户中获取遥测客户端跟踪,您将获得所需的结果,就像我得到的一样。

Program.cs:

using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
    })
    .Build();

host.Run();

希望这有所帮助!

英文:

>How to get Application Insights TelemetryClient in Isolated .NET 7 Azure function?

I have reproduced in my environment and got expected results as below:

.csproj:

&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;
  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net7.0&lt;/TargetFramework&gt;
    &lt;AzureFunctionsVersion&gt;v4&lt;/AzureFunctionsVersion&gt;
    &lt;OutputType&gt;Exe&lt;/OutputType&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
  &lt;/PropertyGroup&gt;
  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.ApplicationInsights.WindowsServer&quot; Version=&quot;2.21.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.ApplicationInsights.WorkerService&quot; Version=&quot;2.21.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.Functions.Worker&quot; Version=&quot;1.10.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.Functions.Worker.Extensions.Http&quot; Version=&quot;3.0.13&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.Functions.Worker.Sdk&quot; Version=&quot;1.7.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.WebJobs.Logging.ApplicationInsights&quot; Version=&quot;3.0.35&quot; /&gt;
  &lt;/ItemGroup&gt;
  &lt;ItemGroup&gt;
    &lt;None Update=&quot;host.json&quot;&gt;
      &lt;CopyToOutputDirectory&gt;PreserveNewest&lt;/CopyToOutputDirectory&gt;
    &lt;/None&gt;
    &lt;None Update=&quot;local.settings.json&quot;&gt;
      &lt;CopyToOutputDirectory&gt;PreserveNewest&lt;/CopyToOutputDirectory&gt;
      &lt;CopyToPublishDirectory&gt;Never&lt;/CopyToPublishDirectory&gt;
    &lt;/None&gt;
  &lt;/ItemGroup&gt;
  &lt;ItemGroup&gt;
    &lt;Using Include=&quot;System.Threading.ExecutionContext&quot; Alias=&quot;ExecutionContext&quot; /&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;

local.settings.json:

{
    &quot;IsEncrypted&quot;: false,
  &quot;Values&quot;: {
    &quot;AzureWebJobsStorage&quot;: &quot;UseDevelopmentStorage=true&quot;,
    &quot;FUNCTIONS_WORKER_RUNTIME&quot;: &quot;dotnet-isolated&quot;,
    &quot;APPINSIGHTS_INSTRUMENTATIONKEY&quot;: &quot;308f2xxxxx039&quot;
  }
}

Function.cs:

using System.Net;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Microsoft.ApplicationInsights.DataContracts;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace FunctionApp23
{
    public class Function1
    {
        public readonly TelemetryClient _tc;
        

        public Function1(TelemetryClient telClient)
        {
            _tc = telClient;
            
        }
        [Function(&quot;Function1&quot;)]
        public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;, &quot;post&quot;)] HttpRequestData req, ILogger log)
        {
            _tc.TrackEvent(&quot;Function is running Rithwik&quot;);

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add(&quot;Content-Type&quot;, &quot;text/plain; charset=utf-8&quot;);

            response.WriteString(&quot;Welcome to Azure Functions!&quot;);

            _tc.TrackEvent(&quot;Function is Completed Rithwik&quot;);

            return response;
        }
    }
}

host.json:

{   &quot;version&quot;: &quot;2.0&quot;,   &quot;logging&quot;: {
    &quot;applicationInsights&quot;: {
      &quot;samplingSettings&quot;: {
        &quot;isEnabled&quot;: true,
        &quot;excludedTypes&quot;: &quot;Request&quot;
      }
    }   
  }
}

Output:

如何在隔离的 .NET 7 Azure 函数中获取 Application Insights TelemetryClient?

如何在隔离的 .NET 7 Azure 函数中获取 Application Insights TelemetryClient?

Then in Portal:

如何在隔离的 .NET 7 Azure 函数中获取 Application Insights TelemetryClient?

如何在隔离的 .NET 7 Azure 函数中获取 Application Insights TelemetryClient?

Try to follow the above steps to get telemetry client traces in portal and you will get required results as I have got.

Program.cs:

using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;


var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =&gt;
    {
        services.AddApplicationInsightsTelemetryWorkerService();
    })
    .Build();

host.Run();



答案2

得分: 0

App Insights支持自动依赖项收集以及应用程序相互调用之间的关联,只需将以下包添加到Azure Function中即可使用。无需安装其他与AppInsights相关的包。

Microsoft.Azure.Functions.Worker.ApplicationInsights 1.0.0-preview4

还需要添加以下program.cs文件:

using Microsoft.Extensions.Hosting;
using Microsoft.Azure.Functions.Worker;

var host = new HostBuilder()
  .ConfigureFunctionsWorkerDefaults((_, builder) =>
  {
      builder
          .AddApplicationInsights()
          .AddApplicationInsightsLogger();
  })
  .Build();

host.Run();

然后,TelemetryClient可以通过DI来使用,所有“正常”数据都将默认收集。

请注意,此包仍处于预览阶段。

英文:

App Insights, with automatic dependency collection and correlation between application calling each other, can be used by adding the following package to the Azure Function.No other AppInsights related packages are needed to be installed.

> Microsoft.Azure.Functions.Worker.ApplicationInsights 1.0.0-preview4

and adding having the following program.cs

using Microsoft.Extensions.Hosting;
using Microsoft.Azure.Functions.Worker;

var host = new HostBuilder()
  .ConfigureFunctionsWorkerDefaults((_, builder) =&gt;
  {
      builder
          .AddApplicationInsights()
          .AddApplicationInsightsLogger();
  })
  .Build();

host.Run();

Then TelemetryClient can be used though DI and all "normal" data will be collected out of the box.

Note that the package is still in preview.

huangapple
  • 本文由 发表于 2023年5月22日 01:06:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定