[英]How to use application insights in .net standard library?
I have used application insights in web api.我在 web api 中使用了应用程序洞察力。 It works well.它运作良好。 Currently, our controller need call a class library (referred by nuget package).目前,我们的 controller 需要调用一个 class 库(参考 nuget 包)。 I need to use application insight in class library.我需要在 class 库中使用应用程序洞察力。 There is no exception but nothing logged in Application insights.没有例外,但没有登录应用程序洞察力。 I write the code as following.我编写代码如下。 Our TelemetryConfiguration have initialized in controller already.我们的 TelemetryConfiguration 已经在 controller 中初始化。
var telemetryClient = new TelemetryClient();
var customEvent = new Microsoft.ApplicationInsights.DataContracts.EventTelemetry
{
Name = "helloworld",
};
// customEvent.Metrics.Add({ "latency", 42});
telemetryClient.TrackEvent(customEvent);
What should I do to make the application insights work?我应该怎么做才能使应用程序洞察力发挥作用?
Normally the following steps are enough to log to App Insights:通常,以下步骤足以登录 App Insights:
1- In your WebApi startup class and your library project add App Insights assembly thru nuget. 1- 在您的 WebApi 启动 class 和您的库项目中,通过 nuget 添加 App Insights 程序集。
Microsoft.ApplicationInsights
2- Register App Insights in your startup class: 2- 在您的启动 class 中注册 App Insights:
services.AddApplicationInsightsTelemetry(Configuration);
3- Setup your instrumentation key in appsettings.json: 3- 在 appsettings.json 中设置您的仪器密钥:
"ApplicationInsights": {
"InstrumentationKey": "<Your instrumentation key here>"
}
4- In any class you need, inject a TelemetryClient and use it. 4- 在您需要的任何 class 中,注入 TelemetryClient 并使用它。
using Microsoft.ApplicationInsights
namespace MyNamesPace
{
public class MyClass
{
private readonly TelemetryClient _telemetryClient;
public MyClass(TelemetryClient telemetryClient)
{
_telemetryClient= telemetryClient;
}
public myClassMethod()
{
// Use your _telemetryClient instance
_telemetryClient.TrackEvent("Your Telemetry Event");
}
}
}
4- In your controller inject your class 4- 在您的 controller 中注入您的 class
namespace MyApiNamesPace
{
public class MyController : ControllerBase
{
private readonly IMyClass _myClass;
public MyClass(IMyClass myClass)
{
_myClass = myClass;
}
public IActionResult myAction()
{
_myClass.MyClassMethod();
}
}
}
5- Don't forget to register your class in your DI container, in startup class: 5- 不要忘记在您的 DI 容器中注册您的 class,在启动 class 中:
services.AddScoped<IMyClass, MyClass>();
Happy programming!!快乐编程!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.