Car*_*var 6 c# exception-handling azure azure-application-insights
实际上,我在我的asp.net web API 2中设置了应用程序见解,以便按照使用Application Insights诊断Web应用程序中的异常的步骤记录错误,一切正常,但是,我想为每个异常添加信息,例如,CustomerId,JobId等.
因此,我希望通过Azure Application Insights在异常(调用堆栈或其他属性)中查看该数据(请参阅此图像).该信息可以帮助我检测我应该用来尝试复制错误场景的记录.
你能告诉我任何建议吗?
谢谢!
据我所知,TelemetryClient.TrackException可以添加自定义属性.
添加这些属性后,您可以在azure洞察门户中找到值.
有关如何在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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在查看所有属性中找到它,如下所示:
但我还有其他问题,如何将数据从我的控制器发送到"AiExceptionLogger".即:我的控制器有POST方法Post(user,jobId),我想将jobId添加到TrackException.注意:我不想对我的控制器中的每个方法使用try {} catch(){},如果我可以将该信息添加到上下文中,那将是grat!.谢谢!
根据你的描述,我建议你可以尝试另一种方式注册过滤器并覆盖OnActionExecuted方法.
在此方法中,您可以首先检查Exception是否为null.如果异常不为null,则可以从HttpActionExecutedContext获取ActionArguments.
然后,您可以在属性中添加此参数,并将它们发送到azure Application Insights.
更多细节,您可以参考以下代码:
WebApiConfig:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
3182 次 |
| 最近记录: |