首页 > 解决方案 > 使用遥测客户端未在 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 上搜索内容我们也找不到任何跟踪或异常。
我们试图强迫TrackTraceTrackExeption并且TrackEvent在那次测试之后我们设法看到了Events在此处输入图像描述 搜索网络将我们带到您可以看到的配置,但仍然不适合我们。

有什么建议吗?提前感谢您的帮助!

标签: c#azureazure-functionsazure-application-insights

解决方案


我怀疑您可能已经配置sampling settingsLogLevel settings在 host.json 文件中。

对于sampling settings,您可以参考配置采样applicationInsights

对于LogLevel,您可以参考配置类别和日志级别

如果不是这样,请告诉我。


推荐阅读