使用 API Application Insights 的良好实践 [英] API Application Insights good practice to use

查看:17
本文介绍了使用 API Application Insights 的良好实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了此文档:https://docs.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics

有许多不同的 API 方法来跟踪异常、跟踪跟踪等.

There are many different API method to track exceptions, track trace etc..

我有一个 ASP.NET MVC 5 应用程序.例如,我有以下控制器方法(由 ajax 调用):

I have a ASP.NET MVC 5 application. For example, I have the following controller method (called by ajax):

    [AjaxErrorHandling]
    [HttpPost]
    public async Task SyncDriverToVistracks(int DriverID)
    {
            if ([condition])
            {
                // some actions here

                try
                {
                    driver.VistrackId = await _vistracksService.AddNewDriverToVistrackAsync(domain);
                    await db.SaveChangesAsync();
                }
                catch (VistracksApiException api_ex)
                {
                    // external service throws exception type VistracksApiException 
                    throw new AjaxException("vistracksApiClient", api_ex.Response.Message);
                }
                catch (VistracksApiCommonException common_ex)
                {
                    // external service throws exception type VistracksApiCommonException 
                    throw new AjaxException("vistracksApiServer", "3MD HOS server is not available");
                }
                catch (Exception ex)
                {
                    // something wrong at all
                    throw new AjaxException("General", ex.Message);
                }
            }
            else
            {
                // condition is not valid
                throw new AjaxException("General", "AccountId is not found");
            }
    }

如果出现问题,此方法会抛出 AjaxException(由 AjaxErrorHandling 捕获,然后向客户端返回一些 json 响应).

this method throws AjaxException if something wrong (which catch by AjaxErrorHandling and then return something json response to client).

现在我想添加遥测来记录日志、分析异常和观察客户端事件.

Now I want to add telemetry for logging, analyzing exceptions and observe on client events.

所以,我添加了以下内容:

So, I added the following:

    [AjaxErrorHandling]
    [HttpPost]
    public async Task SyncDriverToVistracks(int DriverID)
    {
            telemetryClient.TrackEvent("Sync driver", new Dictionary<string, string> { { "ChangedBy", User.Identity.Name }, { "DriverID", DriverID.ToString() } }, null);
            if ([condition])
            {
                // some actions here

                try
                {
                    driver.VistrackId = await _vistracksService.AddNewDriverToVistrackAsync(domain);
                    await db.SaveChangesAsync();
                }
                catch (VistracksApiException api_ex)
                {
                    // external service throws exception type VistracksApiException 
                    telemetryClient.TrackTrace("VistracksApiException", new Dictionary<string, string> {
                        { "ChangedBy", User.Identity.Name },
                        { "DriverID", DriverID.ToString() },
                        { "ResponseCode", api_ex.Response.Code.ToString() },
                        { "ResponseMessage", api_ex.Response.Message },
                        { "ResponseDescription", api_ex.Response.Description }
                    });
                    telemetryClient.TrackException(api_ex);

                    throw new AjaxException("vistracksApiClient", api_ex.Response.Message);
                }
                catch (VistracksApiCommonException common_ex)
                {
                    // external service throws exception type VistracksApiCommonException 
                    telemetryClient.TrackTrace("VistracksApiCommonException", new Dictionary<string, string> {
                        { "ChangedBy", User.Identity.Name },
                        { "DriverID", DriverID.ToString() },
                        { "Message", common_ex.Message },
                    });
                    telemetryClient.TrackException(common_ex);
                    throw new AjaxException("vistracksApiServer", "3MD HOS server is not available");
                }
                catch (Exception ex)
                {
                    // something wrong at all
                    telemetryClient.TrackTrace("Exception", new Dictionary<string, string> {
                        { "ChangedBy", User.Identity.Name },
                        { "DriverID", DriverID.ToString() },
                        { "Message", ex.Message },
                    });
                    telemetryClient.TrackException(ex);
                    throw new AjaxException("General", ex.Message);
                }
            }
            else
            {
                telemetryClient.TrackTrace("ConditionWrong", new Dictionary<string, string> {
                    { "ChangedBy", User.Identity.Name },
                    { "DriverID", DriverID.ToString() },
                    { "Message", "AccountId is not found" },
                });
                // condition is not valid
                throw new AjaxException("General", "AccountId is not found");
            }
    }

通过以下行:

        telemetryClient.TrackEvent("Sync driver", new Dictionary<string, string> { { "ChangedBy", User.Identity.Name }, { "DriverID", DriverID.ToString() } }, null);

我只是记录"客户端事件,即调用了该方法.仅用于统计.

I just "log" client event, that the method was called. Just for statistics.

在每个catch"块中,我尝试使用不同的参数编写跟踪并写入异常:

In each "catch" block I try to write trace with different parameters and write exception:

                    telemetryClient.TrackTrace("trace name", new Dictionary<string, string> {
                        { "ChangedBy", User.Identity.Name },
                        ....
                    });
                    telemetryClient.TrackException(ex);

有必要吗?还是只需要跟踪异常?然后我会丢失不同的信息,例如谁尝试添加这些更改等......应该何时使用这些方法中的每一种?

Is it necessary? Or just need to track only exception? Then I lose different info, like who try to add these changes etc... When each of these methods should be used?

推荐答案

这是 2.5.1 AI SDK 的最佳实践.将突出显示即将发布的 AI SDK 版本中可能不需要的部分.

This is the best practice for 2.5.1 AI SDK. Will highlight parts which might not be required in upcoming AI SDK releases.

进行端到端跟踪的正确方法是依赖 .NET 框架中的新 Activity 类.直到 AI 支持 Activity.Tags (https://github.com/Microsoft/ApplicationInsights-dotnet/问题/562) 您需要使用 TelemetryInitializer:

The right way to do end-to-end tracing is to rely on new Activity class in .NET framework. Until AI supports Activity.Tags (https://github.com/Microsoft/ApplicationInsights-dotnet/issues/562) you need to propagate them manually using TelemetryInitializer:

public class ActvityTagsTelemetryInitializer : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        Activity current = Activity.Current;

        if (current == null)
        {
            current = (Activity)HttpContext.Current?.Items["__AspnetActivity__"];
        }

        while (current != null)
        {
            foreach (var tag in current.Tags)
            {
                if (!telemetry.Context.Properties.ContainsKey(tag.Key))
                {
                    telemetry.Context.Properties.Add(tag.Key, tag.Value);
                }
            }

            current = current.Parent;
        }
    }
}

然后在 ApplicationInsights.config 中注册:

Then register it in ApplicationInsights.config:

  <TelemetryInitializers>
    ...
    <Add Type="<namespace>.ActvityTagsTelemetryInitializer, <assemblyname>"/>
  </TelemetryInitializers>

然后你可以填充适当的标签:

Then you can populate proper tags:

[AjaxErrorHandling]
[HttpPost]
public async Task SyncDriverToVistracks(int DriverID)
{
    Activity.Current.AddTag("DriverID", DriverID.ToString());
    Activity.Current.AddTag("UserID", User.Identity.Name);

    try
    {
        if ([condition])
        {
            // some actions here

            try
            {
                // If below call is HTTP then no need to use StartOperation
                using (telemetryClient.StartOperation<DependencyTelemetry>("AddNewDriverToVistrackAsync"))
                {
                    driver.VistrackId = await _vistracksService.AddNewDriverToVistrackAsync(domain);
                }

                // If below call is HTTP then no need to use StartOperation
                using (telemetryClient.StartOperation<DependencyTelemetry>("SaveChanges"))
                {
                    await db.SaveChangesAsync();
                }
            }
            catch (VistracksApiException api_ex)
            {
                // external service throws exception type VistracksApiException 
                throw new AjaxException("vistracksApiClient", api_ex.Response.Message);
            }
            catch (VistracksApiCommonException common_ex)
            {
                // external service throws exception type VistracksApiCommonException 
                throw new AjaxException("vistracksApiServer", "3MD HOS server is not available");
            }
            catch (Exception ex)
            {
                // something wrong at all
                throw new AjaxException("General", ex.Message);
            }
        }
        else
        {
            // condition is not valid
            throw new AjaxException("General", "AccountId is not found");
        }
    }
    catch (Exception ex)
    {
        // Upcoming 2.6 AI SDK will track exceptions for MVC apps automatically.
        telemetryClient.TrackException(ex);
        throw;
    }
}

您应该具有以下遥测数据:

You should have the following telemetry:

  1. 传入请求
  2. 传出请求(依赖项)
  3. 失败请求的例外

所有遥测数据都将标有 ChangedBy 和 DriverID

All telemetry will be stamped with ChangedBy and DriverID

这篇关于使用 API Application Insights 的良好实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆