遥测客户端未在ApplicationInsights上发布的跟踪和异常

时间:2020-04-16 12:22:49

标签: c# azure-functions azure-application-insights

就是这种情况。

我们有一个由服务总线触发的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上搜索内容时也找不到任何跟踪或异常。
我们尝试强制使用TrackTraceTrackExeptionTrackEvent,在测试之后我们仅看到Eventsenter image description here 搜索网络会将我们引导至您可以看到的配置,但仍然无法为我们服务。

有什么建议吗?预先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我怀疑您可能已经在host.json文件中配置了class ProfileCard extends StatelessWidget { final String imageName; final String title; ProfileCard({this.imageName, this.title}); @override Widget build(BuildContext context) { return Stack( children: [ ClipRRect( borderRadius: BorderRadius.all( Radius.circular(10.0)), child: ShaderMask( shaderCallback: (Rect bounds) { return LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ Colors.transparent, Colors.black ] ).createShader(bounds); }, blendMode: BlendMode.darken, child: Container( width: 400, height: 500, decoration: BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(10.0), ), image: DecorationImage( image: AssetImage('assets/jpg.jpg'), fit: BoxFit.cover, ), ) )) ) ] ); } } sampling settings

对于LogLevel settings,您可以参考Configure samplingapplicationInsights

对于sampling settings,您可以参考Configure categories and log levels

如果不是这种情况,请告诉我。