ApplicationInsights OperationId 为空

Pan*_*wat 3 c# azure azure-application-insights

我正在实现自定义 ApplicationInsights 记录器,并且能够在跟踪、异常和请求等写入位置写入所有日志,但跟踪和异常中的 OperationId 为空。

昨天我使用相同的代码并在所有表中获取 OperationId。之后我在玩多线程场景,效果不佳。现在我用简单的代码重新开始,但看不到 OperationId。

我的代码有什么问题?

public static class Function2
{
    private static TelemetryClient telemetryClient = new TelemetryClient(new Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration
    {
        InstrumentationKey = "********-****-********-****"
    });

    [FunctionName("Function2")]
    public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]HttpRequestMessage req)
    {
        RequestTelemetry requestTelemetry = new RequestTelemetry { Name = "Function2" };
        var operation = telemetryClient.StartOperation(requestTelemetry);

        telemetryClient.TrackTrace("trace message", SeverityLevel.Error);
        telemetryClient.TrackException(new System.Exception("My custom exception"));


        operation.Telemetry.Success = true;
        telemetryClient.StopOperation(operation);

        return req.CreateResponse(HttpStatusCode.OK, "Hello ");
    }
}
Run Code Online (Sandbox Code Playgroud)

Iva*_*ang 7

这个问题很棘手,这是由于仪表键设置。如果您使用Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration(您在代码中使用)设置检测键,则应用洞察中不会出现 operation_id。

所以请使用这行代码来设置检测键:

TelemetryClient telemetryClient = new TelemetryClient() { InstrumentationKey = "your_key" };
Run Code Online (Sandbox Code Playgroud)

我的示例代码如下,仅更改仪表键设置方法:

public static class Function1
{

    private static TelemetryClient telemetryClient = new TelemetryClient() { InstrumentationKey = "your_key" };

    [FunctionName("Function2")]
    public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]HttpRequestMessage req)
    {
        RequestTelemetry requestTelemetry = new RequestTelemetry { Name = "Function211" };
        var operation = telemetryClient.StartOperation(requestTelemetry);

        telemetryClient.TrackTrace("trace message 111", SeverityLevel.Error);
        telemetryClient.TrackException(new System.Exception("My custom exception 111"));

        operation.Telemetry.Success = true;
        telemetryClient.StopOperation(operation);

        return req.CreateResponse(HttpStatusCode.OK, "Hello ");
    }
}
Run Code Online (Sandbox Code Playgroud)

执行后,可以在azure Portal中看到trace/exception的operation_id: 在此处输入图片说明