API Application Insights使用的良好做法 [英] API Application Insights good practice to use

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

问题描述

我阅读了此文档:有许多不同的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");
            }
    }

如果出现错误(此错误由AjaxErrorHandling捕获,然后向客户端返回json响应),则此方法将引发AjaxException.

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/issue/562 ),则需要使用

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;
    }
}

您应该进行以下遥测:

  1. 传入请求
  2. 去向请求(依赖项)
  3. 失败请求的异常

所有遥测都将带有ChangedBy和DriverID标记

All telemetry will be stamped with ChangedBy and DriverID

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

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