示例#1
0
        /// <summary>
        /// Uploads all log entries that contains an exception to codeRR.
        /// </summary>
        /// <param name="loggingEvent">The logging event.</param>
        protected override void Append(LoggingEvent loggingEvent)
        {
            LogsProvider.Instance.Add(new LogEntryDto(loggingEvent.TimeStampUtc, ConvertLevel(loggingEvent.Level), loggingEvent.RenderedMessage)
            {
                Exception = loggingEvent.ExceptionObject?.ToString(),
                Source    = loggingEvent.LoggerName,
            });
            if (loggingEvent.ExceptionObject == null)
            {
                return;
            }

            IErrorReporterContext context = new ErrorReporterContext(this, loggingEvent.ExceptionObject);
            var dataCollection            = new LogEntryDetails
            {
                LogLevel   = loggingEvent.Level.ToString(),
                Message    = loggingEvent.RenderedMessage,
                ThreadName = loggingEvent.ThreadName,
                Timestamp  = loggingEvent.TimeStamp,
                LoggerName = loggingEvent.LoggerName,
                UserName   = loggingEvent.UserName
            }.ToContextCollection("LogEntry");

            context.ContextCollections.Add(dataCollection);

            var coderrCollection = context.ContextCollections.GetCoderrCollection();

            coderrCollection.Properties[CoderrCollectionProperties.HighlightCollection] = "LogEntry";

            Err.Report(context);
        }
示例#2
0
        private IMessageInvoker MessageInvokerFactory(IHandlerScope arg)
        {
            var k       = arg.ResolveDependency <IMessageHandler <FeedbackAttachedToIncident> >();
            var invoker = new MessageInvoker(arg);

            invoker.HandlerMissing += (sender, args) =>
            {
                _logger.Warn(
                    "Failed to find a handler for " + args.Message.Body.GetType());
            };
            invoker.HandlerInvoked += (sender, args) =>
            {
                if (args.Exception == null)
                {
                    return;
                }

                Err.Report(args.Exception,
                           new { args.Message, HandlerType = args.Handler.GetType(), args.ExecutionTime });
                _logger.Error(
                    $"Ran {args.Handler}, took {args.ExecutionTime.TotalMilliseconds}ms, but FAILED.",
                    args.Exception);
            };
            return(invoker);
        }
        ///<inheritdoc />
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Exception != null)
            {
                filterContext.Controller.ViewData.ModelState.AddModelError("", filterContext.Exception.Message);
                filterContext.ExceptionHandled = true;

                var model = filterContext.Controller.ViewData.Model
                            ?? filterContext.HttpContext.Items["AttachedCoderrModel"];
                if (model is IDictionary <string, object> )
                {
                    model = model.ToContextCollection("Model");
                }
                if (model != null)
                {
                    Err.Report(filterContext.Exception, model);
                }
                else
                {
                    Err.Report(filterContext.Exception);
                }

                filterContext.Result = CreateView(filterContext);
                return;
            }
            base.OnActionExecuted(filterContext);
        }
        private IMessageInvoker MessageInvokerFactory(IHandlerScope arg)
        {
            var invoker = new MessageInvoker(arg);

            invoker.HandlerMissing += (sender, args) =>
            {
                _log.Warn("Handler missing for " + args.Message.Body.GetType());
            };
            invoker.Logger          = DiagnosticLog;
            invoker.HandlerInvoked += (sender, args) =>
            {
                _log.Debug(args.Message.Body);
                if (args.Exception == null)
                {
                    return;
                }

                Err.Report(args.Exception, new
                {
                    args.Message.Body,
                    HandlerType = args.Handler.GetType(),
                    args.ExecutionTime
                });
                _log.Error(
                    $"Ran {args.Handler}, took {args.ExecutionTime.TotalMilliseconds}ms, but FAILED.",
                    args.Exception);
            };
            return(invoker);
        }
示例#5
0
 private void FilterAndSubmit(Exception ex)
 {
     if (ShouldSubmit(ex))
     {
         Err.Report(ex);
     }
 }
 private void OnBackgroundJobFailed(object sender, BackgroundJobFailedEventArgs e)
 {
     Err.Report(e.Exception, new
     {
         JobType = e.Job.GetType().FullName
     });
 }
        private QueueListener ConfigureQueueListener(ConfigurationContext context, string inboundQueueName,
                                                     string outboundQueueName)
        {
            var inboundQueue  = _messageQueueProvider.Open(inboundQueueName);
            var outboundQueue = inboundQueueName == outboundQueueName
                ? inboundQueue
                : _messageQueueProvider.Open(outboundQueueName);
            var scopeFactory = new ScopeWrapper(context.ServiceProvider);
            var router       = new MessageRouter
            {
                ReportAnalyzerQueue = outboundQueue,
                AppQueue            = _messageQueueProvider.Open("Messaging")
            };

            var listener = new QueueListener(inboundQueue, router, scopeFactory)
            {
                RetryAttempts = new[]
                { TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2) },
                MessageInvokerFactory = scope =>
                {
                    var invoker = new MessageInvoker(scope);
                    invoker.Logger          += (level, name, message) => _logger.Debug("[" + name + "] " + message);
                    invoker.InvokingHandler += (sender, args) =>
                    {
                        _logger.Debug(
                            $"Invoking {JsonConvert.SerializeObject(args.Message)} ({args.Handler.GetType()}).");
                    };
                    return(invoker);
                },
                Logger = DiagnosticLog
            };

            listener.PoisonMessageDetected += (sender, args) =>
            {
                Err.Report(args.Exception, new { args.Message.Body });
                _logger.Error(inboundQueueName + " Poison message: " + args.Message.Body, args.Exception);
            };
            listener.ScopeCreated += (sender, args) =>
            {
                args.Scope.ResolveDependency <IPrincipalAccessor>().First().Principal = args.Principal;

                _logger.Debug(inboundQueueName + " Running " + args.Message.Body + ", Credentials: " +
                              args.Principal.ToFriendlyString());
            };
            listener.ScopeClosing += (sender, args) =>
            {
                if (args.Exception != null)
                {
                    return;
                }

                var all = args.Scope.ResolveDependency <IAdoNetUnitOfWork>().ToList();
                all[0].SaveChanges();

                var queue = (DomainQueueWrapper)args.Scope.ResolveDependency <IDomainQueue>().First();
                queue.SaveChanges();
            };
            listener.MessageInvokerFactory = MessageInvokerFactory;
            return(listener);
        }
        public override void Log(ExceptionLoggerContext context)
        {
            var data = "";

            if (context.Request.Content != null)
            {
                data = context.Request.Content.ReadAsStringAsync().Result;
            }

            _logger.Error("Request + " + context.Request.RequestUri + ", data" + data, context.Exception);
            _logger.Error(context.Exception);

            var properties = new Dictionary <string, string>
            {
                { "Url", context.Request.RequestUri.ToString() },
                { "HttpMethod", context.Request.Method.Method }
            };

            if (context.Request.Headers.Referrer != null)
            {
                properties.Add("Referer", context.Request.Headers.Referrer.ToString());
            }
            if (data.Length < 30000)
            {
                properties.Add("Body", data);
            }
            var collection = new ContextCollectionDTO("Request", properties);

            Err.Report(context.Exception, collection);
            base.Log(context);
        }
示例#9
0
        private void SendErrorInternal(bool useAsync, Exception ex, object context = null)
        {
            if (!IsConfigured)
            {
                return;
            }

            if (!useAsync)
            {
                if (context == null)
                {
                    Err.Report(ex);
                }
                else
                {
                    Err.Report(ex, context);
                }
            }
            else
            {
                Task.Factory.StartNew(() =>
                {
                    if (context == null)
                    {
                        Err.Report(ex);
                    }
                    else
                    {
                        Err.Report(ex, context);
                    }
                });
            }
        }
        private void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();

            var data = "";

            if ((Request.InputStream != null) && (Request.InputStream.Length > 0))
            {
                var reader = new StreamReader(Request.InputStream);
                data = reader.ReadToEnd();
            }
            _logger.Error("Request + " + Request.Url + ", data" + data, exception);

            var properties = new Dictionary <string, string>
            {
                { "Url", Request.Url.ToString() },
                { "HttpMethod", Request.HttpMethod }
            };

            if (Request.UrlReferrer != null)
            {
                properties.Add("Referrer", Request.UrlReferrer.ToString());
            }
            if (data.Length < 30000)
            {
                properties.Add("Body", data);
            }
            properties.Add("ErrTags", "unhandled-exception");
            var collection = new ContextCollectionDTO("Request", properties);

            Err.Report(exception, collection);
        }
示例#11
0
 private void FilterAndSubmit(string format, Exception ex, object[] args)
 {
     if (ShouldSubmit(ex))
     {
         Err.Report(ex, TryFormat(format, args));
     }
 }
示例#12
0
 private void OnBackgroundJobFailed(object sender, BackgroundJobFailedEventArgs e)
 {
     _logger.Error("Report Job failed: " + e.Job, e.Exception);
     Err.Report(e.Exception, new
     {
         JobType = e.Job.GetType().FullName
     });
 }
 private void OnServiceFailed(object sender, ApplicationServiceFailedEventArgs e)
 {
     _log.Error("Failed to execute " + e.ApplicationService, e.Exception);
     try
     {
         Err.Report(e.Exception, new { JobType = e.ApplicationService?.GetType().FullName });
     }
     catch (Exception exception)
     {
         _log.Error("Failed to report.", exception);
     }
 }
 private void OnJobFailed(object sender, BackgroundJobFailedEventArgs e)
 {
     _log.Error("Failed to execute " + e.Job, e.Exception);
     try
     {
         Err.Report(e.Exception, new { JobType = e.Job?.GetType().FullName });
     }
     catch (Exception ex)
     {
         _log.Error("Failed to report.", ex);
     }
 }
示例#15
0
 private void OnBackgroundJobScopeClosing(object sender, ScopeClosingEventArgs e)
 {
     try
     {
         e.Scope.Resolve <IAdoNetUnitOfWork>().SaveChanges();
     }
     catch (Exception exception)
     {
         Err.Report(e.Exception);
         _log.Error("Failed to close scope. Err: " + exception, e.Exception);
     }
 }
示例#16
0
        /// <inheritdoc />
        public void Emit(LogEvent logEvent)
        {
            var message = logEvent.RenderMessage(_formatProvider);
            var entry   = new LogEntryDto(logEvent.Timestamp.ToUniversalTime().DateTime, ConvertLevel(logEvent.Level),
                                          message)
            {
                Exception = logEvent.Exception?.ToString(),
            };

            LogsProvider.Instance.Add(entry);

            if (logEvent.Exception != null)
            {
                Err.Report(logEvent.Exception, entry);
            }
        }
        public void Should_be_able_to_report_error_with_client_lib_and_error_shows_up_in_incidents()
        {
            UITest(() =>
            {
                var url = new Uri(ServerUrl);
                Err.Configuration.Credentials(url, TestData.Application.AppKey, TestData.Application.SharedSecret);
                Err.Report(new ArgumentNullException("id"), new { SampleData = "Context example" });

                // Give the server some time to process the incident
                Thread.Sleep(3000);

                var sut = new IncidentsPage(WebDriver, 1);
                sut.NavigateToPage();

                sut.VerifyIncidentReported();
            });
        }
示例#18
0
        public async Task Upload_a_report_with_anonymous_object()
        {
            var methodName = nameof(Upload_a_report_with_anonymous_object);
            var uid        = Guid.NewGuid().ToString();

            try
            {
                throw new InvalidOperationException(methodName + " " + uid);
            }
            catch (Exception ex)
            {
                Err.Report(ex, new { Mark = true });
            }

            var actual = await _client.GetReport(methodName, uid);

            actual.CollectionProperty("ContextData", "Mark").Should().Be("True");
        }
示例#19
0
        public async Task Upload_a_report_without_extra_data()
        {
            var methodName = nameof(Upload_a_report_without_extra_data);
            var uid        = Guid.NewGuid().ToString();

            try
            {
                throw new InvalidOperationException(methodName + " " + uid);
            }
            catch (Exception ex)
            {
                Err.Report(ex);
            }

            var actual = await _client.CheckIfReportExists(methodName, uid);

            actual.Should().BeTrue();
        }
        private IMessageInvoker CreateMessageInvoker(IServiceProvider x)
        {
            var provider = (ServiceProvider)x;
            var invoker  = new MessageInvoker(new HandlerScopeWrapper(provider));

            invoker.HandlerMissing += (sender, args) =>
            {
                _log.Error("No handler for " + args.Message.Body.GetType());
                try
                {
                    throw new NoHandlerRegisteredException(
                              "Failed to find a handler for " + args.Message.Body.GetType());
                }
                catch (Exception ex)
                {
                    Err.Report(ex, new { args.Message.Body });
                }
            };

            invoker.InvokingHandler += (sender, args) =>
            {
                _log.Debug($"Invoking {JsonConvert.SerializeObject(args.Message)} ({args.Handler.GetType()}).");
            };
            invoker.HandlerInvoked += (sender, args) =>
            {
                _log.Debug($".. completed {args.Handler.GetType()}");
                if (args.Exception == null)
                {
                    return;
                }

                _log.Error(
                    $"Ran {args.Handler}, took {args.ExecutionTime.TotalMilliseconds}ms, but FAILED.",
                    args.Exception);

                Err.Report(args.Exception, new
                {
                    args.Message.Body,
                    HandlerType = args.Handler.GetType(),
                    args.ExecutionTime
                });
            };
            return(invoker);
        }
示例#21
0
        private void UpgradeDatabaseSchema()
        {
            // Dont run for new installations
            if (!HostConfig.Instance.IsConfigured)
            {
                return;
            }

            try
            {
                var migrator = new MigrationRunner(() => OpenConnection(CoderrClaims.SystemPrincipal), "Coderr", typeof(CoderrMigrationPointer).Namespace);
                migrator.Run();
            }
            catch (Exception ex)
            {
                _logger.Fatal("DB Migration failed.", ex);
                Err.Report(ex, new { Migration = true });
            }
        }
示例#22
0
        public async Task should_tag_incident_when_ErrTags_is_added_to_a_collection()
        {
            var methodName = nameof(should_tag_incident_when_ErrTags_is_added_to_a_collection);
            var id         = Guid.NewGuid().ToString();

            try
            {
                throw new InvalidDataException(methodName + " " + id);
            }
            catch (Exception ex)
            {
                Err.Report(ex, new { ErrTags = "important,data" });
            }

            var incident = await _client.GetIncident(methodName, id);

            incident.Tags.Should().Contain("important");
            incident.Tags.Should().Contain("data");
        }
示例#23
0
        public void Execute(HttpErrorReporterContext context)
        {
            try
            {
                if (ExecuteUserController(context.HttpContext))
                {
                    return;
                }
                if (ExecuteUserView(context.HttpContext))
                {
                    return;
                }

                BuiltInViewRender.Render(context);
            }
            catch (Exception ex)
            {
                Err.Report(ex, new { context.HttpStatusCodeName, context.HttpStatusCode });
            }
        }
示例#24
0
        public async Task should_tag_incident_when_collectionBuilder_is_used()
        {
            var methodName = nameof(should_tag_incident_when_collectionBuilder_is_used);
            var id         = Guid.NewGuid().ToString();

            try
            {
                throw new InvalidDataException(methodName + " " + id);
            }
            catch (Exception ex)
            {
                var collection = CollectionBuilder.CreateTags("max", "overdrive");
                Err.Report(ex, collection);
            }

            var incident = await _client.GetIncident(methodName, id);

            incident.Tags.Should().Contain("max");
            incident.Tags.Should().Contain("overdrive");
        }
示例#25
0
        /// <summary>
        ///     Writes logging event to the log target. Must be overridden in inheriting
        ///     classes.
        /// </summary>
        /// <param name="logEvent">Logging event to be written out.</param>
        protected override void Write(LogEventInfo logEvent)
        {
            LogsProvider.Instance.Add(new LogEntryDto(logEvent.TimeStamp.ToUniversalTime(), ConvertLevel(logEvent.Level), logEvent.Message)
            {
                Exception = logEvent.Exception?.ToString(),
                Source    = logEvent.LoggerName,
            });

            if (logEvent.Exception == null)
            {
                return;
            }

            Err.Report(logEvent.Exception, new
            {
                ErrTags = "nlog,level-" + logEvent.Level,
                logEvent.TimeStamp,
                Message = logEvent.FormattedMessage
            });
        }
示例#26
0
 public static void ThrowImportantError()
 {
     try
     {
         throw new NotSupportedException("Not invented here");
     }
     catch (Exception ex)
     {
         Err.Report(ex, new
         {
             myData  = "hello",
             ErrTags = "important",
             Adress  =
                 new
             {
                 City = "Falun"
             }
         });
     }
 }
        /// <summary>
        /// Uploads all log entries that contains an exception to codeRR.
        /// </summary>
        /// <param name="loggingEvent">The logging event.</param>
        protected override void Append(LoggingEvent loggingEvent)
        {
            LogsProvider.Instance.Add(new LogEntryDto(loggingEvent.TimeStampUtc, ConvertLevel(loggingEvent.Level), loggingEvent.RenderedMessage)
            {
                Exception = loggingEvent.ExceptionObject.ToString(),
                Source    = loggingEvent.LoggerName,
            });
            if (loggingEvent.ExceptionObject == null)
            {
                return;
            }

            Err.Report(loggingEvent.ExceptionObject, new LogEntryDetails
            {
                LogLevel   = loggingEvent.Level.ToString(),
                Message    = loggingEvent.RenderedMessage,
                ThreadName = loggingEvent.ThreadName,
                Timestamp  = loggingEvent.TimeStamp
            });
        }
示例#28
0
        static void Main(string[] args)
        {
            var url = new Uri("http://localhost:50473/");

            Err.Configuration.Credentials(url,
                                          "ae0428b701054c5d9481024f81ad8b05",
                                          "988cedd2bf4641d1aa228766450fab97");


            Err.ReportLogicError("User should have been assigned.");
            try
            {
                throw new NotSupportedException("Not invented here");
            }
            catch (Exception ex)
            {
                Err.Report(ex, new { myData = "hello", ErrTags = "important" });
            }
            Console.WriteLine("Hello World!");
        }
示例#29
0
        private void UpgradeDatabaseSchema()
        {
            // Dont run for new installations
            if (!IsConfigured)
            {
                return;
            }

            try
            {
                var migrator = new SchemaManager(() => OpenConnection(CoderrClaims.SystemPrincipal));
                if (migrator.CanSchemaBeUpgraded())
                {
                    migrator.UpgradeDatabaseSchema();
                }
            }
            catch (Exception ex)
            {
                _logger.Error("DB Migration failed.", ex);
                Err.Report(ex, new { Migration = true });
            }
        }
示例#30
0
        private void ReportSlowMessageHandler(IInvokeHandlerContext context, TimeSpan elapsed)
        {
            var ex  = new SlowMessageHandlerException(context.MessageHandler.HandlerType.Name, elapsed);
            var ctx = new NServiceBusContext(this, ex)
            {
                HandlerInstance = context.MessageHandler.Instance,
                HandlerType     = context.MessageHandler.HandlerType,
                Body            = context.MessageBeingHandled,
                Metadata        = context.MessageMetadata,
                MessageType     = context.MessageMetadata.MessageType,
                IsHandled       = !context.HandlerInvocationAborted,
                MessageHeaders  = context.MessageHeaders,
                MessageId       = context.MessageId,
                ReplyToAddress  = context.ReplyToAddress
            };

            ctx.AddHighlightedProperty("MessageHandler", "Type");
            ctx.AddHighlightedCollection("MessageBody");
            ctx.AddTag("performance");
            ctx.AddTag("nservicebus");

            Err.Report(ctx);
        }