将 TelemetryClient 的静态实例与 Application Insights 结合使用

Using Static Instance of TelemetryClient with Application Insights

我有一个 ASP.NET MVC 网站,我正在实施 Application Insights。现在,我记录一个跟踪事件如下:

private static TelemetryClient _APM;
private static TelemetryClient APM
{
    get
    {
        if (_APM == null) { _APM = new TelemetryClient(); }
        return _APM;
    }
}

public static void Trace(string Message)
{
    APM.TrackTrace(Message);
}

如您所见,这将为所有跟踪维护 TelemetryClient 的单个静态实例。这是我们应该如何使用客户端吗?或者我们应该为每个日志创建一个新的 TelemetryClient 实例?

根据 the docs 你应该:

... use an instance of TelemetryClient for each module of your app. For instance, you may have one TelemetryClient in your web service to report incoming http requests, and another in a middleware class to report business logic events.

为每个日志创建一个新的遥测客户端可能很昂贵,因此根据您的应用程序的结构,您可能正确地使用您在 post.[=12 中描述的单例模式=]

darth_phoenixx 引用的完整引用实际上是:

TelemetryClient is thread-safe.

For ASP.NET and Java projects, incoming HTTP Requests are automatically captured. You might want to create additional instances of TelemetryClient for other module of your app. For instance, you may have one TelemetryClient instance in your middleware class to report business logic events. You can set properties such as UserId and DeviceId to identify the machine. This information is attached to all events that the instance sends.

TelemetryClient.Context.User.Id = "...";
TelemetryClient.Context.Device.Id = "...";

最后一点非常重要。如果您正在编写类似于 UserId 可能更改的 Web 应用程序,您可能应该为每个范围重用遥测客户端的实例,其中这些值都相同(如每个请求),但不是 static/singleton实例.

更新

在 ASP.NET Core 中,Application Insights 大量使用依赖注入并将 TelemetryClient 注册为单例!

这意味着您应该避免在您不希望在整个应用程序中使用的客户端上下文中设置变量,而是利用遥测初始化器来设置类似用户的内容每个遥测对象的 ID。