c# - 使用遥测客户端未在 ApplicationInsights 上发布的跟踪和异常
问题描述
情况就是这样。
我们有一个由服务总线触发的 Azure 函数,它应该收集消息并将它们发布到 ApplicationInsights。
这就是我们为函数编写的代码
public class TopicToApplicationInsightsLogs
{
private readonly IApplicationInsightsService _appInsightsService;
public TopicToApplicationInsightsLogs(IApplicationInsightsService appInsightsService)
{
_appInsightsService = appInsightsService;
}
[FunctionName("TopicToApplicationInsightsLogs")]
public async Task Run(
[ServiceBusTrigger("%MonitorLogTopic%", "%MonitorLogSubcription%", Connection = "MonitorLogServiceBusConnectionString")]
string jsonData,
ILogger log,
MessageReceiver messageReceiver,
string lockToken
)
{
var jObject = JObject.Parse(jsonData);
var data = jObject.GetValue("Data").ToObject<Common.Domain.Payloads.Entities.MonitorLog>();
try
{
foreach (var edgeLog in data.Data.Logs)
{
_appInsightsService.TrackTrace(edgeLog);
if (!string.IsNullOrWhiteSpace(edgeLog.SerializedException))
{
_appInsightsService.TrackException(edgeLog);
}
_appInsightsService.Flush();
}
await messageReceiver.CompleteAsync(lockToken);
log.LogInformation($"Posted {data.Data.Logs.Count()} posts.");
}
catch (Exception ex)
{
await messageReceiver.DeadLetterAsync(lockToken);
log.LogError($"Error posting logs: {ex.Message}", ex);
throw;
}
}
}
这就是ApplicationInsightsService.cs
内容
public class ApplicationInsightsService : IApplicationInsightsService
{
private readonly TelemetryClient _telemetryClient;
public ApplicationInsightsService()
{
var appInsightsConnectionString = Environment.GetEnvironmentVariable("ApplicationInsightsConnectionString", EnvironmentVariableTarget.Process);
var appInsightsInstrumentationKey = Environment.GetEnvironmentVariable("ApplicationInsightsInstrumentationKey", EnvironmentVariableTarget.Process);
var config = TelemetryConfiguration.CreateDefault();
config.ConnectionString = appInsightsConnectionString;
//config.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
_telemetryClient = new TelemetryClient(config)
{
InstrumentationKey = appInsightsInstrumentationKey
};
//_telemetryClient.Context.User.Id = Assembly.GetExecutingAssembly().GetName().Name;
//_telemetryClient.Context.Device.Id = Environment.MachineName;
}
public void TrackTrace(MonitorLogDataRecord log)
{
var traceTelemetry = log.ToTraceTelemetry();
_telemetryClient.TrackTrace(traceTelemetry);
}
public void TrackException(MonitorLogDataRecord log)
{
var exception = log.ToExceptionTelemetry();
_telemetryClient.TrackException(exception);
}
public void TrackEvent(MonitorLogDataRecord log)
{
var dict = new Dictionary<string, string> {{"log", JsonConvert.SerializeObject(log)}};
_telemetryClient.TrackEvent("Test", dict);
}
public void Flush()
{
_telemetryClient.Flush();
// Argh
//Task.Delay(5000).Wait();
}
}
和ApplicationInsightsParser.cs
用于映射对象
public static class ApplicationInsightsParser
{
public static TraceTelemetry ToTraceTelemetry(this MonitorLogDataRecord log)
{
return new TraceTelemetry
{
Timestamp = log.Timestamp,
//Properties = {{"", ""}},
Context =
{
//Component =
//{
// Version = ""
//},
//Device =
//{
// Id = "",
// Model = "",
// OemName = "",
// OperatingSystem = "",
// Type = ""
//},
//Cloud =
//{
// RoleInstance = "",
// RoleName = ""
//},
//Flags = 0,
//InstrumentationKey = "",
//Location =
//{
// Ip = ""
//},
Operation =
{
Name = log.Source
//CorrelationVector = "",
//Id = "",
//ParentId = "",
//SyntheticSource = ""
}
//Session =
//{
// Id = "",
// IsFirst = true
//},
//User =
//{
// Id = "",
// AccountId = "",
// AuthenticatedUserId = "",
// UserAgent = ""
//},
//GlobalProperties = {{"", ""}}
},
//Extension = null,
//Sequence = "",
//ProactiveSamplingDecision =SamplingDecision.None,
Message = log.Content,
SeverityLevel = log.Level.ParseToSeverity()
};
}
public static ExceptionTelemetry ToExceptionTelemetry(this MonitorLogDataRecord log)
{
return new ExceptionTelemetry
{
Timestamp = log.Timestamp,
//Properties = {{"", ""}},
Context =
{
//Component =
//{
// Version = ""
//},
//Device =
//{
// Id = "",
// Model = "",
// OemName = "",
// OperatingSystem = "",
// Type = ""
//},
//Cloud =
//{
// RoleInstance = "",
// RoleName = ""
//},
//Flags = 0,
//InstrumentationKey = "",
//Location =
//{
// Ip = ""
//},
Operation =
{
Name = log.Source
//CorrelationVector = "",
//Id = "",
//ParentId = "",
//SyntheticSource = ""
}
//Session =
//{
// Id = "",
// IsFirst = true
//},
//User =
//{
// Id = "",
// AccountId = "",
// AuthenticatedUserId = "",
// UserAgent = ""
//},
//GlobalProperties =
//{
// {"", ""}
//}
},
//Extension = null,
//Sequence = "",
//ProactiveSamplingDecision = SamplingDecision.None,
//Message = log.Content,
SeverityLevel = log.Level.ParseToSeverity(),
//Metrics =
//{
// {"", 0}
//},
Exception = JsonConvert.DeserializeObject<Exception>(log.SerializedException)
//ProblemId = ""
};
}
private static SeverityLevel ParseToSeverity(this MonitorLogDataRecordLevel logLevel)
{
switch (logLevel)
{
case MonitorLogDataRecordLevel.Debug:
return SeverityLevel.Verbose;
case MonitorLogDataRecordLevel.Info:
return SeverityLevel.Information;
case MonitorLogDataRecordLevel.Warn:
return SeverityLevel.Warning;
case MonitorLogDataRecordLevel.Error:
return SeverityLevel.Error;
case MonitorLogDataRecordLevel.Fatal:
return SeverityLevel.Critical;
default:
throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null);
}
}
}
该服务被实例化为单例使用Startup.cs
,但即使我们在运行时得到 0 个错误并且我们看到来自正在处理的队列中的消息,在 ApplicationInsighs 上搜索内容我们也找不到任何跟踪或异常。
我们试图强迫TrackTrace
,TrackExeption
并且TrackEvent
在那次测试之后我们设法看到了Events
。
搜索网络将我们带到您可以看到的配置,但仍然不适合我们。
有什么建议吗?提前感谢您的帮助!
解决方案
我怀疑您可能已经配置sampling settings
或LogLevel settings
在 host.json 文件中。
对于sampling settings
,您可以参考配置采样和applicationInsights。
对于LogLevel
,您可以参考配置类别和日志级别。
如果不是这样,请告诉我。
推荐阅读
- python-2.7 - 我需要帮助来解码这个输出。我使用过 python 文件操作。谁能告诉我为什么我得到这个输出
- c# - 使用 C# 连接数据库
- java - Android - 更改所有 Android 版本的应用程序语言
- android - Android MotionLayout:MotionScene 未触发
- python - 使用 Falcon RES API 提供 pdf 文件
- excel - 使用 VBA 在 Excel 中将多个文本转换为列
- pdf - Ghostscript:错误:使用 %003d 时,pdfmark 目标页面 x 指向最后一页 y 之外
- html - 正则表达式:仅转换 url "http|https" 外部元素
- html - 如何在单列网格中浮动引导卡
- html - 在顶部栏中的菜单按钮旁边定位页面标题