Трассировки и исключения не публикуются в ApplicationInsights с клиентом телеметрии - PullRequest
0 голосов
/ 16 апреля 2020

Это ситуация.

У нас есть функция 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 content

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. enter image description here Поиск в Интернете приводит нас к конфигурации, которую вы видите, но все еще не работает для нас.

Есть какие-нибудь предложения? Заранее спасибо за любую помощь!

1 Ответ

1 голос
/ 24 апреля 2020

Я подозреваю, что вы, возможно, настроили sampling settings или LogLevel settings в хосте. json файл.

Для sampling settings вы можете обратиться к Настройка выборки и applicationInsights .

Для LogLevel вы можете обратиться к Настройка категорий и уровней журнала .

Если это не так, пожалуйста, дайте мне знать .

...