如何让Azure在日志中保留ASP.NET Core异常消息?
解决Azure Application Insights剥离异常消息的问题
下面是几种可行的解决方法,你可以逐一尝试:
1. 自定义遥测初始化器强制保留异常消息
默认的Application Insights遥测处理可能会过滤异常消息,你可以通过自定义初始化器强制保留:
创建自定义初始化器类:
using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility; public class ExceptionMessageTelemetryInitializer : ITelemetryInitializer { public void Initialize(ITelemetry telemetry) { if (telemetry is ExceptionTelemetry exceptionTelemetry && exceptionTelemetry.Exception != null) { exceptionTelemetry.Message = exceptionTelemetry.Exception.Message; // 若需要完整异常栈信息,可添加此行 // exceptionTelemetry.Properties["FullException"] = exceptionTelemetry.Exception.ToString(); } } }
在Program.cs中注册该初始化器:
builder.Services.AddApplicationInsightsTelemetry(); builder.Services.AddSingleton<ITelemetryInitializer, ExceptionMessageTelemetryInitializer>();
2. 检查日志级别配置
确保Application Insights能收集到对应级别的异常日志。在appsettings.json中调整日志配置:
{ "Logging": { "ApplicationInsights": { "LogLevel": { "Default": "Error", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } } } }
确保异常对应的日志级别(如Error)被设置为允许收集,否则消息可能不会被上报。
3. 确认自定义异常的实现正确性
如果StrangeException是自定义异常,要保证消息能被正确传递到基类:
public class StrangeException : Exception { public int StatusCode { get; } public StrangeException(int statusCode, string message) : base(message) { StatusCode = statusCode; } }
必须通过base(message)将消息传递给Exception基类的Message属性,否则Application Insights无法读取到消息内容。
4. 关闭敏感数据过滤(谨慎使用)
Azure的安全机制可能会过滤敏感内容,若你的异常消息不含敏感信息,可在appsettings.json中禁用过滤:
{ "ApplicationInsights": { "SensitiveData": { "DisableFiltering": true } } }
注意:此操作可能带来安全风险,生产环境需谨慎使用,确保异常消息无敏感数据。
内容的提问来源于stack exchange,提问作者baddie
相关产品推荐
相关产品推荐

