gpt4 book ai didi

c# - Application Insights - 异常添加信息

转载 作者:太空狗 更新时间:2023-10-29 21:16:24 26 4
gpt4 key购买 nike

实际上,我在 ASP.NET Web API 2 中设置了应用程序见解,以按照步骤 Diagnose exceptions in your web apps with Application Insights 记录错误,一切工作正常,但是,我想为每个异常添加信息,例如 CustomerId、JobId 等。

因此,我希望通过 Azure Application Insights ( see this image ) 查看异常中的数据(调用堆栈或其他属性)。该信息可以帮助我检测应该使用哪些记录来尝试复制错误场景。

你能告诉我什么建议吗?

谢谢!

最佳答案

据我所知,TelemetryClient.TrackException 可以添加自定义属性。

添加这些属性后,您可以在 Azure Insights 门户中找到值。

更多关于如何在Web api中添加自定义属性的详细信息,您可以引用以下代码:

  public class AiExceptionLogger : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
if (context != null && context.Exception != null)
{//or reuse instance (recommended!). see note above
var ai = new TelemetryClient();
//Here you need get the CustomerId, JobId, and other. For example get the current user id
string re = HttpContext.Current.User.Identity.Name;

// Set up some properties:
//Here you need get what you need and add them to the properties
var properties = new Dictionary<string, string> {{ "Users", "vvvvv" } };
// Send the exception telemetry:
ai.TrackException(context.Exception, properties);
}
base.Log(context);
}
}

您可以在“查看所有属性”中找到它,如下所示:

enter image description here

<小时/>

But I have other question, How can I do to send data from my controller to "AiExceptionLogger". i.e: I have my controller a POST method Post(user, jobId), I want to add jobId to TrackException. Note: I don't want to use try{} catch(){} for every method in my controller, If I can add that information to context, it will be grat!. Thanks!

根据您的描述,我建议您可以尝试其他方式注册过滤器并覆盖 OnActionExecuted 方法。

在此方法中,您可以首先检查异常是否为空。如果异常不为 null,您可以从 HttpActionExecutedContext 获取 ActionArguments。

然后您可以在属性中添加此参数并将它们发送到 azure Application Insights。

更多详细信息,您可以引用以下代码:

WebApi配置:

public static void Register(HttpConfiguration config)
{
// Web API configuration and services

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

//config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());

config.Filters.Add(new AAA());
}

public class AAA : ActionFilterAttribute
{

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception != null)
{
var ai = new TelemetryClient();
//here get the arguments
string d1 = (string)actionExecutedContext.ActionContext.ActionArguments["id"];
var properties = new Dictionary<string, string> { { "Users", d1 } };
ai.TrackException(actionExecutedContext.Exception, properties);
}
base.OnActionExecuted(actionExecutedContext);
}
}

结果:

enter image description here enter image description here

关于c# - Application Insights - 异常添加信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44356883/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com