Application Insights - Logging exceptions

前端 未结 2 1650
我寻月下人不归
我寻月下人不归 2020-12-17 21:32

I wrote a custom logger for Application Insights in my app. I don\'t see any exceptions or ANY events when viewing App Insights in Azure Portal. Here is the logger class cod

2条回答
  •  离开以前
    2020-12-17 21:51

    I created a new Console Application, installed latest stable ApplicationInsights SDK and pretty much kept your example, with minor but important difference - I either let it wait before shutting down after calling TrackException or added TelemetryClient.Flush()

    namespace logtest
    {
        class Program
        {
            static void Main(string[] args)
            {
                AppInsightsLogger logger = new AppInsightsLogger();
                logger.LogException(new InvalidOperationException("Is data showing?"));
    
                // either wait for a couple of minutes for the batch to be sent of add ai.Flush() after ai.TrackException() to send the batch immediately
                Console.ReadLine();
            }
        }
    
        public class AppInsightsLogger
        {
            private TelemetryClient ai;
    
            public AppInsightsLogger()
            {
                ai = new TelemetryClient();
                if (string.IsNullOrEmpty(ai.InstrumentationKey))
                {
                    // attempt to load instrumentation key from app settings
                    var appSettingsTiKey = "";
                    if (!string.IsNullOrEmpty(appSettingsTiKey))
                    {
                        TelemetryConfiguration.Active.InstrumentationKey = appSettingsTiKey;
                        ai.InstrumentationKey = appSettingsTiKey;
                    }
                    else
                    {
                        throw new Exception("Could not find instrumentation key for Application Insights");
                    }
                }
            }
            public void LogException(Exception ex)
            {
                ai.TrackException(ex);
                // ai.Flush();
            }
        }
    }
    

    First I could see telemetry item sent in Visual Studio debug output window:

    Then I could see telemetry leaving my machine in Fiddler, I also could see it was successfully accepted by our data collection endpoint.

    And finally I could see it in the portal:

提交回复
热议问题