public Task PublishAsync(HealthReport report, CancellationToken cancellationToken)
        {
            foreach (var keyedEntry in report.Entries)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                var    key   = keyedEntry.Key;
                var    entry = keyedEntry.Value;
                Status dataDogStatus;

                switch (entry.Status)
                {
                case HealthStatus.Healthy:
                    dataDogStatus = Status.OK;
                    break;

                case HealthStatus.Degraded:
                    dataDogStatus = Status.WARNING;
                    break;

                case HealthStatus.Unhealthy:
                    dataDogStatus = Status.CRITICAL;
                    break;

                default:
                    dataDogStatus = Status.UNKNOWN;
                    break;
                }

                var tags = _defaultTags.Concat(new[]
                {
                    $"check:{key}"
                }).ToArray();

                var message = entry.Description ?? entry.Status.ToString();
                _dogStatsd.ServiceCheck(_serviceCheckName, dataDogStatus, null, Environment.MachineName, tags, message);
                _dogStatsd.Timer(_serviceCheckName, entry.Duration.TotalMilliseconds, 1, tags);
            }

            return(Task.CompletedTask);
        }
Example #2
0
        /// <inheritdoc />
        public async Task HandleNotificationAsync(MessageReceivedNotification notification, CancellationToken cancellationToken = default)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            if (!(notification.Message is IUserMessage userMessage) ||
                (userMessage.Author is null))
            {
                return;
            }

            if (!(userMessage.Author is IGuildUser author) ||
                (author.Guild is null) ||
                author.IsBot ||
                author.IsWebhook)
            {
                return;
            }

            var argPos = 0;

            if (!userMessage.HasCharPrefix('!', ref argPos) && !userMessage.HasMentionPrefix(DiscordClient.CurrentUser, ref argPos))
            {
                return;
            }

            if (userMessage.Content.Length <= 1)
            {
                return;
            }

            var commandContext = new CommandContext(DiscordClient, userMessage);

            await AuthorizationService.OnAuthenticatedAsync(author);

            IResult commandResult = null;
            var     commandTimer  = Stopwatch.StartNew();

            try
            {
                commandResult = await CommandService.ExecuteAsync(commandContext, argPos, ServiceProvider);
            }
            finally
            {
                commandTimer.Stop();
                var duration = commandTimer.ElapsedMilliseconds;

                if (!(_stats is null) && (commandResult.IsSuccess || !string.Equals(commandResult.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase)))
                {
                    var commandInfo = CommandService.Search(commandContext, argPos).Commands.FirstOrDefault();
                    var name        = commandInfo.Command?.Name.ToLowerInvariant();

                    _stats?.Timer("command_duration_ms", duration,
                                  tags: new[] { $"guild:{commandContext.Guild.Name}", $"success:{commandResult.IsSuccess}", $"command:{name}" });
                }
            }

            if (!commandResult.IsSuccess)
            {
                var error = $"{commandResult.Error}: {commandResult.ErrorReason}";

                if (string.Equals(commandResult.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase))
                {
                    Log.Error(error);
                }
                else
                {
                    Log.Warning(error);
                }

                if (commandResult.Error == CommandError.Exception)
                {
                    await commandContext.Channel.SendMessageAsync($"Error: {FormatUtilities.SanitizeEveryone(commandResult.ErrorReason)}");
                }
                else
                {
                    await CommandErrorHandler.AssociateError(userMessage, error);
                }
            }

            stopwatch.Stop();
            Log.Information($"Command took {stopwatch.ElapsedMilliseconds}ms to process: {commandContext.Message}");
        }
Example #3
0
        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            if (_statsd == null)
            {
                // I know it sounds crazy at first, but because OnEventSourceCreated is called from the base constructor,
                // and EnableEvents is called from OnEventSourceCreated, it's entirely possible that OnEventWritten
                // gets called before the child constructor is called.
                // In that case, just bail out.
                return;
            }

            try
            {
                if (eventData.EventName == "EventCounters")
                {
                    ExtractCounters(eventData.Payload);
                }
                else if (eventData.EventId == EventGcSuspendBegin)
                {
                    _gcStart = eventData.TimeStamp;
                }
                else if (eventData.EventId == EventGcRestartEnd)
                {
                    var start = _gcStart;

                    if (start != null)
                    {
                        _statsd.Timer(MetricsNames.GcPauseTime, (eventData.TimeStamp - start.Value).TotalMilliseconds);
                        Log.Debug("Sent the following metrics: {metrics}", MetricsNames.GcPauseTime);
                    }
                }
                else
                {
                    if (eventData.EventId == EventGcHeapStats)
                    {
                        var stats = HeapStats.FromPayload(eventData.Payload);

                        _statsd.Gauge(MetricsNames.Gen0HeapSize, stats.Gen0Size);
                        _statsd.Gauge(MetricsNames.Gen1HeapSize, stats.Gen1Size);
                        _statsd.Gauge(MetricsNames.Gen2HeapSize, stats.Gen2Size);
                        _statsd.Gauge(MetricsNames.LohSize, stats.LohSize);

                        Log.Debug("Sent the following metrics: {metrics}", GcHeapStatsMetrics);
                    }
                    else if (eventData.EventId == EventContentionStop)
                    {
                        var durationInNanoseconds = (double)eventData.Payload[2];

                        _contentionTime.Time(durationInNanoseconds / 1_000_000);
                        Interlocked.Increment(ref _contentionCount);
                    }
                    else if (eventData.EventId == EventGcGlobalHeapHistory)
                    {
                        var heapHistory = HeapHistory.FromPayload(eventData.Payload);

                        if (heapHistory.MemoryLoad != null)
                        {
                            _statsd.Gauge(MetricsNames.GcMemoryLoad, heapHistory.MemoryLoad.Value);
                        }

                        _statsd.Increment(GcCountMetricNames[heapHistory.Generation], 1, tags: heapHistory.Compacting ? CompactingGcTags : NotCompactingGcTags);
                        Log.Debug("Sent the following metrics: {metrics}", GcGlobalHeapMetrics);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warning <int, string>(ex, "Error while processing event {EventId} {EventName}", eventData.EventId, eventData.EventName);
            }
        }
 private void GcPauseTime(TimeSpan timespan)
 {
     _statsd.Timer("runtime.dotnet.gc.pause_time", timespan.TotalMilliseconds);
 }