コード例 #1
0
 protected override void LogMessageCore(string message, IDictionary <string, string> additionalData, Severity severity)
 {
     if (telemetry.IsEnabled())
     {
         telemetry.TrackTrace(new TraceTelemetry(message)
         {
             Timestamp     = DateTimeProvider.Now,
             SeverityLevel = MapSeverityLevel(severity)
         });
     }
 }
コード例 #2
0
ファイル: AppStart.cs プロジェクト: olevett/website
        public Action <IApplicationBuilder> Configure(Action <IApplicationBuilder> next) => app =>
        {
            // Enable tracking of application start/stop to Application Insights
            if (_telemetry.IsEnabled())
            {
                _appLifetime.ApplicationStarted.Register(() =>
                {
                    var startedEvent = new EventTelemetry("Application Started");
                    _telemetry.TrackEvent(startedEvent);
                });
                _appLifetime.ApplicationStopping.Register(() =>
                {
                    var startedEvent = new EventTelemetry("Application Stopping");
                    _telemetry.TrackEvent(startedEvent);
                });
                _appLifetime.ApplicationStopped.Register(() =>
                {
                    var stoppedEvent = new EventTelemetry("Application Stopped");
                    _telemetry.TrackEvent(stoppedEvent);
                    _telemetry.Flush();

                    // Allow some time for flushing before shutdown.
                    Thread.Sleep(1000);
                });
            }

            // Call next now so that the ILoggerFactory by Startup.Configure is configured before we go any further
            next(app);

            // Prime the cached web root file provider for static file serving
            _cachedWebRoot.PrimeCache();
        };
コード例 #3
0
 private bool TelemetryIsEnabled()
 {
     return(_configurationProvider.WebTrackerIsEnabled() &&
            telemetryClient != null &&
            !string.IsNullOrEmpty(telemetryClient.InstrumentationKey) &&
            telemetryClient.IsEnabled());
 }
コード例 #4
0
 /// <summary>
 /// Tracks the given record.
 /// </summary>
 /// <param name="record"></param>
 /// <param name="timeout"></param>
 protected override void Track(TrackingRecord record, TimeSpan timeout)
 {
     if (telemetryClient.IsEnabled())
     {
         TrackRecord(record);
     }
 }
コード例 #5
0
        private static void ReloadConfig()
        {
            if (File.Exists("config.json"))
            {
                try
                {
                    string str = File.ReadAllText("config.json");
                    Config = JsonConvert.DeserializeObject <Config>(str);

                    if (Config == null)
                    {
                        ConfigLoadFailure(buffer, new NullReferenceException());
                    }
                }
                catch (Exception ex)
                {
                    ConfigLoadFailure(buffer, ex);
                }
            }
            else
            {
                Config = new Config();
                File.WriteAllText("config.json", JsonConvert.SerializeObject(Config));
            }

            _saveTimer?.Stop();
            _saveTimer = new Timer(30_000)
            {
                AutoReset = true
            };
            _saveTimer.Elapsed += SaveTimer_Elapsed;
            _saveTimer.Start();

            _statusTimer?.Stop();
            _statusTimer = new Timer(Config.StatusUpdateInterval.TotalMilliseconds)
            {
                AutoReset = true
            };
            _statusTimer.Elapsed += UpdateStatusTimer;
            _statusTimer.Start();

            TelemetryClient?.Flush();
            if (Config.ApplicationInsightsKey != Guid.Empty)
            {
                TelemetryConfiguration.Active.InstrumentationKey = Config.ApplicationInsightsKey.ToString();
                TelemetryClient = new TelemetryClient();
                TelemetryClient.TrackEvent(new EventTelemetry("Startup"));

                AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

                _appLogArea.WriteLine($"Application Insights telemetry configured! {TelemetryClient.IsEnabled()}");
            }
            else
            {
                _appLogArea.WriteLine("Application Insights telemetry id unavailable, disabling...");
                TelemetryConfiguration.Active.DisableTelemetry = true;
            }
        }
コード例 #6
0
        /// <summary>
        /// Implement OnException method of IExceptionFilter which will be invoked
        /// for all unhandled exceptions
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            this._logger.LogError("MatterCenterExceptionFilter", context.Exception);
            var        stackTrace         = new StackTrace(context.Exception, true);
            StackFrame stackFrameInstance = null;

            if (stackTrace.GetFrames().Length > 0)
            {
                for (int i = 0; i < stackTrace.GetFrames().Length; i++)
                {
                    if (stackTrace.GetFrames()[i].ToString().Contains("Microsoft.Legal.Matter"))
                    {
                        stackFrameInstance = stackTrace.GetFrames()[i];
                        break;
                    }
                }
            }
            //Create custom exception response that needs to be send to client
            var response = new ErrorResponse()
            {
                Message     = context.Exception.Message,
                StackTrace  = context.Exception.ToString(),
                Description = "Error occured in the system. Please contact the administrator",
                //Exception = context.Exception.ToString(),
                LineNumber = stackFrameInstance?.GetFileLineNumber(),
                MethodName = stackFrameInstance?.GetMethod().Name,
                ClassName  = stackFrameInstance?.GetMethod().DeclaringType.Name,
                ErrorCode  = ((int)HttpStatusCode.InternalServerError).ToString()
            };

            //Create properties that need to be added to application insights
            var properties = new Dictionary <string, string>();

            properties.Add("StackTrace", response.StackTrace);
            properties.Add("LineNumber", response.LineNumber.ToString());
            properties.Add("MethodName", response.MethodName.ToString());
            properties.Add("ClassName", response.ClassName.ToString());
            properties.Add("ErrorCode", response.ErrorCode.ToString());

            //Create Telemetry object to add exception to the application insights
            var ai = new TelemetryClient();

            ai.InstrumentationKey = instrumentationKey;
            if (ai.IsEnabled())
            {
                //add exception to the Application Insights
                ai.TrackException(context.Exception, properties);
            }

            //Send the exceptin object to the client
            context.Result = new ObjectResult(response)
            {
                StatusCode   = (int)HttpStatusCode.InternalServerError,
                DeclaredType = typeof(ErrorResponse)
            };
        }
コード例 #7
0
        private void TrackShowEvent(AdminInputModel input, LiveShowDetails liveShowDetails)
        {
            if (_telemetry.IsEnabled())
            {
                var showStarted = string.IsNullOrEmpty(liveShowDetails.LiveShowEmbedUrl) && !string.IsNullOrEmpty(input.LiveShowEmbedUrl);
                var showEnded   = !string.IsNullOrEmpty(liveShowDetails.LiveShowEmbedUrl) && string.IsNullOrEmpty(input.LiveShowEmbedUrl);

                if (showStarted || showEnded)
                {
                    var showEvent = new EventTelemetry(showStarted ? "Show Started" : "Show Ended");
                    showEvent.Properties.Add("Show Embed URL", showStarted ? input.LiveShowEmbedUrl : liveShowDetails.LiveShowEmbedUrl);
                    _telemetry.TrackEvent(showEvent);
                }
            }
        }
コード例 #8
0
        public Action <IApplicationBuilder> Configure(Action <IApplicationBuilder> next) => app =>
        {
            // Work around Application Insights issue breaking Azure Storage: https://github.com/Microsoft/ApplicationInsights-aspnetcore/issues/416
            var modules          = app.ApplicationServices.GetServices <ITelemetryModule>();
            var dependencyModule = modules.OfType <DependencyTrackingTelemetryModule>().FirstOrDefault();
            if (dependencyModule != null)
            {
                var domains = dependencyModule.ExcludeComponentCorrelationHttpHeadersOnDomains;
                domains.Add("core.windows.net");
                domains.Add("core.chinacloudapi.cn");
                domains.Add("core.cloudapi.de");
                domains.Add("core.usgovcloudapi.net");
            }

            // Enable tracking of application start/stop to Application Insights
            if (_telemetry.IsEnabled())
            {
                _appLifetime.ApplicationStarted.Register(() =>
                {
                    var startedEvent = new EventTelemetry("Application Started");
                    _telemetry.TrackEvent(startedEvent);
                });
                _appLifetime.ApplicationStopping.Register(() =>
                {
                    var stoppingEvent = new EventTelemetry("Application Stopping");
                    _telemetry.TrackEvent(stoppingEvent);
                    _telemetry.Flush();
                });
                _appLifetime.ApplicationStopped.Register(() =>
                {
                    var stoppedEvent = new EventTelemetry("Application Stopped");
                    _telemetry.TrackEvent(stoppedEvent);
                    _telemetry.Flush();

                    // Allow some time for flushing before shutdown.
                    Thread.Sleep(1000);
                });
            }

            // Call next now so that the ILoggerFactory by Startup.Configure is configured before we go any further
            next(app);

            // Prime the cached web root file provider for static file serving
            _cachedWebRoot.PrimeCache();
        };
コード例 #9
0
 private void TrackDependency(CloudBlockBlob blockBlob, string operation, long length, long started, bool succeeded)
 {
     if (_telemetry.IsEnabled())
     {
         var duration   = Timing.GetDuration(started);
         var dependency = new DependencyTelemetry
         {
             Type      = "Storage",
             Target    = blockBlob.StorageUri.PrimaryUri.Host,
             Name      = blockBlob.Name,
             Data      = operation,
             Timestamp = DateTimeOffset.UtcNow,
             Duration  = duration,
             Success   = succeeded
         };
         dependency.Metrics.Add("Size", length);
         dependency.Properties.Add("Storage Uri", blockBlob.StorageUri.PrimaryUri.ToString());
         _telemetry.TrackDependency(dependency);
     }
 }
コード例 #10
0
        /// <summary>
        /// profile with results.
        /// </summary>
        /// <param name="type">The type of execution.</param>
        /// <param name="func">a function to execute against against the profile result</param>
        /// <typeparam name="TResult">the type of result to return.</typeparam>
        private TResult TrackDependency <TResult>(string type, Func <TResult> func)
        {
            if (telemetryClient == null || !telemetryClient.IsEnabled())
            {
                return(func());
            }

            var     success   = false;
            var     startTime = DateTime.UtcNow;
            var     timer     = System.Diagnostics.Stopwatch.StartNew();
            TResult result;

            try
            {
                result  = func();
                success = true;
            }
            finally
            {
                timer.Stop();
                var dependencyType      = _command.GetType().FullName;
                var dependencyTelemetry = new DependencyTelemetry(dependencyType, type, startTime, timer.Elapsed, success);
                dependencyTelemetry.DependencyTypeName = dependencyType;

                StringBuilder builder = new StringBuilder();
                builder.Append(_command.CommandText);
                builder.AppendLine();
                builder.AppendLine();
                foreach (DbParameter parameter in _command.Parameters)
                {
                    builder.AppendLine(string.Format("{0} = {1}", parameter.ParameterName, parameter.Value.ToString()));
                }

                dependencyTelemetry.Properties.Add(new KeyValuePair <string, string>("commandText", builder.ToString()));
                telemetryClient.TrackDependency(dependencyTelemetry);
            }

            return(result);
        }
コード例 #11
0
        private static void Main(string[] args)
        {
            // TODO: Add your own instrumentation key.
            const string instrumentationKey = "4fe9fc01-23cc-40ee-94e1-6dc532d861b9";

            var telemetryConfiguration = new TelemetryConfiguration(instrumentationKey);
            var telemetryClient        = new TelemetryClient(telemetryConfiguration);

            if (!telemetryClient.IsEnabled())
            {
                Console.Write("TelemetryClient is not enabled.");
                return;
            }
            var period = TimeSpan.FromSeconds(10);

            ProfilingServices.Initialize(telemetryClient, period);

            Console.WriteLine($"Sampling every {period.TotalSeconds} seconds. Press Ctrl-C to stop, then wait a few seconds for completion.");

            Console.CancelKeyPress += OnCancel;

            var threads = new Thread[16];

            for (var i = 0; i < threads.Length; i++)
            {
                threads[i] = new Thread(ThreadMain);
                threads[i].Start();
            }

            foreach (var thread in threads)
            {
                thread.Join();
            }

            telemetryClient.Flush();
            Console.WriteLine("Done");
        }
コード例 #12
0
        protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            try
            {
                if (request != null && response != null && (_telemetryClient?.IsEnabled() ?? false))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        var telemetry = new DependencyTelemetry();
                        telemetry.Type = "Http";
                        telemetry.Data = await request.Content?.ReadAsStringAsync();

                        telemetry.Name       = $"{request.Method.Method} {request.RequestUri.AbsolutePath}";
                        telemetry.Target     = request.RequestUri?.ToString();
                        telemetry.ResultCode = response.StatusCode.ToString();
                        telemetry.Properties.Add("Telemetry Source", "HttpClientAppInsightsHandler");
                        telemetry.Properties.Add("Request Headers", request.Headers.ToString());
                        telemetry.Properties.Add("Request Content Headers", request.Content.Headers.ToString());
                        telemetry.Properties.Add("Response Headers", response.Headers.ToString());
                        telemetry.Properties.Add("Response Body", await response.Content?.ReadAsStringAsync());
                        telemetry.Success = false;
                        _telemetryClient.TrackDependency(telemetry);
                    }
                }
            }
            catch
            {
                // Swallow as we don't want this to break anything.
            }

            return(response);
        }
コード例 #13
0
ファイル: BotContext.cs プロジェクト: eclipseanu/WamBot
        public async Task ConnectAsync()
        {
            if (_connected)
            {
                throw new InvalidOperationException("God you're a twat.");
            }

            if (!liteMode)
            {
                _statusTimer?.Stop();
                _statusTimer = new Timer(_config.StatusUpdateInterval.TotalMilliseconds)
                {
                    AutoReset = true
                };
                _statusTimer.Elapsed += _statusTimer_Elapsed;
                _statusTimer.Start();
            }

            _telemetryClient?.Flush();
            if (_config.ApplicationInsightsKey != Guid.Empty && !liteMode)
            {
                TelemetryConfiguration.Active.InstrumentationKey = _config.ApplicationInsightsKey.ToString();
                _telemetryClient = new TelemetryClient();
                _telemetryClient.TrackEvent(new EventTelemetry("Startup"));

                AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

                LogMessage?.Invoke(this, $"Application Insights telemetry configured! {_telemetryClient.IsEnabled()}");
            }
            else
            {
                LogMessage?.Invoke(this, "Application Insights telemetry id unavailable, disabling...");
                TelemetryConfiguration.Active.DisableTelemetry = true;
            }

            await LoadPluginsAsync();

            LogMessage?.Invoke(this, "Connecting to Discord... ");

            await _discordClient.ConnectAsync();
        }
コード例 #14
0
 public bool isEnabled()
 {
     return(tClient.IsEnabled());
 }
コード例 #15
0
 /// <summary>
 /// Return <c>true</c> if the telemetry client is enabled.  \1est
 /// </summary>
 /// <param name="level">Level is ignored for this implementation.</param>
 /// <param name="category">Category is ignored for this implementation.</param>
 /// <returns></returns>
 public override bool ShouldLog(LoggingLevel level, string category)
 {
     return(_telemetryClient.IsEnabled());
 }
コード例 #16
0
        public override void Write(string message)
        {
            if (string.IsNullOrWhiteSpace(message) || !IsC1FunctionMessage(message))
            {
                return;
            }

            var telemetryClient = new TelemetryClient(TelemetryConfiguration.Active);

            if (!telemetryClient.IsEnabled())
            {
                return;
            }

            var c1Severity = GetPropertyValue(message, _rd[C1MessageProps.C1Severity]);
            var aiSeverity = GetAISeverity(c1Severity);

            var callStackContent = GetCallStackContent(message);

            var exceptionType = GetPropertyValue(message, _rd[C1MessageProps.ExceptionType]);
            var functionName  = GetPropertyValue(message, _rd[C1MessageProps.FunctionName]);
            var priority      = GetPropertyValue(message, _rd[C1MessageProps.Priority]);
            var machine       = GetPropertyValue(message, _rd[C1MessageProps.Machine]);
            var appDomain     = GetPropertyValue(message, _rd[C1MessageProps.AppDomain]);
            var processId     = GetPropertyValue(message, _rd[C1MessageProps.ProcessId]);

            DependencyTelemetry dependencyTelemetry = new DependencyTelemetry()
            {
                Type    = "C1 Function",
                Success = aiSeverity == SeverityLevel.Information
            };

            dependencyTelemetry.Properties.Add(C1Function, functionName);

            var telemetryExceptionProperties = new Dictionary <string, string>()
            {
                { "Function Name", functionName },
                { "Priority", priority },
                { "Machine", machine },
                { "App Domain", appDomain },
                { "Process ID", processId }
            };

            using (var operation = telemetryClient.StartOperation(dependencyTelemetry))
            {
                ExceptionDetailsInfo exceptionDetailsInfo = new ExceptionDetailsInfo(
                    0,
                    0,
                    exceptionType,
                    $"{aiSeverity}: {functionName}",
                    !string.IsNullOrWhiteSpace(callStackContent),
                    callStackContent,
                    new List <StackFrame>());

                var exception = new ExceptionTelemetry(
                    new List <ExceptionDetailsInfo>()
                {
                    exceptionDetailsInfo
                },
                    aiSeverity,
                    null,
                    telemetryExceptionProperties,
                    new Dictionary <string, double>());

                telemetryClient.TrackException(exception);
            }
        }
コード例 #17
0
 /// <inheritdoc />
 public bool IsEnabled(LogLevel logLevel)
 {
     return(filter != null && telemetryClient != null && filter(categoryName, logLevel) && telemetryClient.IsEnabled());
 }
コード例 #18
0
 public TelemetryLogger(TelemetryClient telemetryClient)
 {
     this._telemetryClient = telemetryClient;
     this.IsEnabled        = telemetryClient.IsEnabled();
 }