public void Log(object logMessage, LogLevel logLevel, params string[] vals) { if (logLevel == LogLevel.Critical && logMessage is Exception exception && !(exception is NonLoggableException)) { var sentryEvent = new SentryEvent(exception); lock (_lockingObject) { foreach (var contextKeyValue in ContextData) { sentryEvent.SetExtra(contextKeyValue.Key, contextKeyValue.Value); } SentryClient.CaptureEvent(sentryEvent); } } }
public static void Warning(string message) { if (client == null) { setupClient(); } var sentryEvent = new SentryEvent(message) { Level = ErrorLevel.Warning }; client?.CaptureAsync(sentryEvent); Log.Warning(message); }
public static string CaptureException(Exception ex) { var plugins = PluginManager.Instance.Plugins.Where(x => x.IsEnabled).ToList(); ex.Data.Add("active-plugins", plugins.Any() ? string.Join(", ", plugins.Select(x => x.NameAndVersion)) : "none"); var exception = new SentryEvent(ex); #if (SQUIRREL) exception.Tags.Add("squirrel", "true"); #else exception.Tags.Add("squirrel", "false"); #endif exception.Tags.Add("hearthstone", Helper.GetHearthstoneBuild()?.ToString()); return(Client.Capture(exception)); }
public async Task Invoke(HttpContext context) { string message = $"Request for {context.Request.Path} with trace id {context.TraceIdentifier} received ({context.Request.ContentLength ?? 0} bytes).\r\n" + $"Request headers: {DictionaryToString(context.Request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString()))}\r\n" + $"Request host: {context.Request.Host}\r\n" + $"Response headers: {DictionaryToString(context.Response.Headers.ToDictionary(h => h.Key, h => h.Value.ToString()))}\r\n" + $"Response status code: {context.Response.StatusCode}"; SentryEvent sentryEvent = new SentryEvent(message); sentryEvent.Level = ErrorLevel.Info; _ravenClient.Capture(sentryEvent); await _next.Invoke(context); }
public static void Exception(Exception exception) { if (client == null) { setupClient(); } var sentryEvent = new SentryEvent(exception) { Level = ErrorLevel.Error }; client?.CaptureAsync(sentryEvent); Log.Exception(exception); }
public void Process_InnerExceptionHasAggregateExceptionDupe_ReturnsNull() { _fixture.Options.DeduplicateMode |= DeduplicateMode.InnerException; var duplicate = new Exception(); var first = new SentryEvent(new InvalidOperationException("test", new AggregateException(duplicate))); var second = new SentryEvent(new InvalidOperationException("another test", new Exception("testing", new AggregateException(duplicate)))); var sut = _fixture.GetSut(); _ = sut.Process(first); var actual = sut.Process(second); Assert.Null(actual); }
public void Process_ExceptionProcessors_Invoked() { var exceptionProcessor = Substitute.For <ISentryEventExceptionProcessor>(); _fixture.SentryOptions.AddExceptionProcessorProvider(() => new[] { exceptionProcessor }); var sut = _fixture.GetSut(); var evt = new SentryEvent { Exception = new Exception() }; sut.Process(evt); exceptionProcessor.Received(1).Process(evt.Exception, evt); }
public void Process_NoEnvironmentOnOptions_SameAsEnvironmentVariable() { const string expected = "Staging"; var sut = _fixture.GetSut(); var evt = new SentryEvent(); EnvironmentVariableGuard.WithVariable( Constants.EnvironmentEnvironmentVariable, expected, () => { sut.Process(evt); }); Assert.Equal(expected, evt.Environment); }
public async Task <string> CaptureMessageAsync(SentryMessage message, ErrorLevel level = ErrorLevel.Info, IDictionary <string, string> tags = null, string[] fingerprint = null, object extra = null) { var @event = new SentryEvent(message) { Level = level, Extra = extra, Tags = tags, Fingerprint = fingerprint }; return(await CaptureAsync(@event)); }
public void Dispose_TokenCancelledWhenRequestInFlight_StopsTask() { var evt = new SentryEvent(); _ = _fixture.Transport .CaptureEventAsync(evt, Arg.Any <CancellationToken>()) .Throws(new OperationCanceledException()); var sut = _fixture.GetSut(); _ = sut.EnqueueEvent(evt); sut.Dispose(); Assert.Equal(TaskStatus.RanToCompletion, sut.WorkerTask.Status); }
/// <summary>Captures the event.</summary> /// <param name="event">The event.</param> /// <returns> /// The <see cref="JsonPacket.EventID" /> of the successfully captured <paramref name="exception" />, or <c>null</c> if it fails. /// </returns> public async Task <string> CaptureAsync(SentryEvent @event) { @event.Tags = MergeTags(@event.Tags); if (!this.breadcrumbs.IsEmpty()) { @event.Breadcrumbs = this.breadcrumbs.ToList(); } var packet = this.jsonPacketFactory.Create(CurrentDsn.ProjectID, @event); var eventId = await SendAsync(packet); RestartTrails(); return(eventId); }
public void IterationSetup() { _backgroundWorker = new BackgroundWorker(new FakeTransport(), new SentryOptions { MaxQueueItems = 1000 }); _event = new SentryEvent(); _envelope = Envelope.FromEvent(_event); // Make sure worker spins once. _backgroundWorker.EnqueueEnvelope(_envelope); _backgroundWorker.FlushAsync(TimeSpan.FromSeconds(10)).GetAwaiter().GetResult(); for (var i = 0; i < Items; i++) { _backgroundWorker.EnqueueEnvelope(_envelope); } }
public SentryId CaptureEvent(SentryEvent evt, Scope?scope = null) { try { var currentScope = ScopeManager.GetCurrent(); var actualScope = scope ?? currentScope.Key; var id = currentScope.Value.CaptureEvent(evt, actualScope); actualScope.LastEventId = id; return(id); } catch (Exception e) { _options.DiagnosticLogger?.LogError("Failure to capture event: {0}", e, evt.EventId); return(SentryId.Empty); } }
public void Process_NoExceptionOnEvent_ExceptionProcessorsNotInvoked() { var invoked = false; SentryOptions.AddExceptionProcessorProvider(() => { invoked = true; return(new[] { Substitute.For <ISentryEventExceptionProcessor>() }); }); var evt = new SentryEvent(); Sut.Process(evt); Assert.False(invoked); }
public string CaptureMessage(SentryMessage message, ErrorLevel level = ErrorLevel.Info, IDictionary <string, string> tags = null, string[] fingerprint = null, object extra = null) { var @event = new SentryEvent(message) { Level = level, Extra = extra, Tags = MergeTags(tags), Fingerprint = fingerprint }; return(Capture(@event)); }
public static void Error(string message, Exception exception, IEnumerable <KeyValuePair <string, string> > extraTags) { SentryEvent sentryEvent = new SentryEvent(exception) { Message = message, Level = Sentry.Protocol.SentryLevel.Error, }; if (extraTags != null) { sentryEvent.SetTags(extraTags); } sentryEvent.SetTag("HRESULT", exception.HResult.ToString()); SentrySdk.CaptureEvent(sentryEvent); }
private void PrepareEvent(SentryEvent @event) { if (Version != "") // version override { @event.release = Version; } if (SendDefaultPii) { @event.contexts.device.name = SystemInfo.deviceName; } @event.tags.deviceUniqueIdentifier = SystemInfo.deviceUniqueIdentifier; @event.extra.unityVersion = Application.unityVersion; @event.extra.screenOrientation = Screen.orientation.ToString(); }
/// <summary> /// Writes logging event to the log target. /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected override void Write(LogEventInfo logEvent) { try { Dictionary <string, string> extras = SendLogEventInfoPropertiesAsTags ? null : logEvent.Properties.ToDictionary(x => x.Key.ToString(), x => x.Value.ToString()); client.Value.Logger = logEvent.LoggerName; // If the log event did not contain an exception and we're not ignoring // those kinds of events then we'll send a "Message" to Sentry if (logEvent.Exception == null && !IgnoreEventsWithNoException) { var sentryMessage = new SentryMessage(Layout.Render(logEvent)); var sentryEvent = new SentryEvent(sentryMessage) { Level = LoggingLevelMap[logEvent.Level], Extra = extras, Fingerprint = { logEvent.UserStackFrame?.ToString(), logEvent.LoggerName }, Tags = { { ServiceNameKey, ServiceName } } }; client.Value.Capture(sentryEvent); } else if (logEvent.Exception != null) { var sentryMessage = new SentryMessage(logEvent.FormattedMessage); var sentryEvent = new SentryEvent(logEvent.Exception) { Extra = new Dictionary <string, string> { { RawStackTraceKey, logEvent.Exception.StackTrace } }, Level = LoggingLevelMap[logEvent.Level], Message = sentryMessage, Fingerprint = { logEvent.UserStackFrame?.ToString(), logEvent.LoggerName }, Tags = { { ServiceNameKey, ServiceName } } }; client.Value.Capture(sentryEvent); } } catch (Exception ex) { LogException(ex); } }
public void Process_InnerExceptionHasAggregateExceptionDupe_ReturnsNull() { var duplicate = new Exception(); var first = new SentryEvent { Exception = new InvalidOperationException("test", new AggregateException(duplicate)) }; var second = new SentryEvent { Exception = new InvalidOperationException("another test", new Exception("testing", new AggregateException(duplicate))) }; _ = _sut.Process(first); var actual = _sut.Process(second); Assert.Null(actual); }
private static SentryEvent SentryBeforeSend(SentryEvent args) { args.User = new User { Id = AssistantOptions.UserId }; args.SetTag("SessionId", AssistantOptions.SessionId); args.SetExtra("PlayerName", Engine.Player?.Name ?? "Unknown"); args.SetExtra("PlayerSerial", Engine.Player?.Serial ?? 0); args.SetExtra("Shard", Engine.CurrentShard?.Name ?? "Unknown"); args.SetExtra("ShardFeatures", Engine.Features.ToString()); args.SetExtra("Connected", Engine.Connected); args.SetExtra("ClientVersion", Engine.ClientVersion == null ? "Unknown" : Engine.ClientVersion.ToString()); args.SetExtra("KeyboardLayout", InputLanguageManager.Current?.CurrentInputLanguage?.Name ?? "Unknown"); return(args); }
public static void UseSentry(this IApplicationBuilder builder, string dsn) { if (string.IsNullOrWhiteSpace(dsn)) { // No need to put in the middleware if there is no Sentry configuration return; } builder.Use(async(context, next) => { try { await next.Invoke().ConfigureAwait(false); } catch (Exception ex) { var client = context.RequestServices.GetService <IRavenClient>(); if (string.IsNullOrWhiteSpace(client?.CurrentDsn?.ProjectID)) { // There is no client or no configuration for Sentry throw; } var sentryEvent = new SentryEvent(ex); // This is a workaround while SharpRaven support doesn't quite support asp.net core var user = context?.Request?.HttpContext?.User?.Identity?.Name; if (string.IsNullOrWhiteSpace(user) == false) { sentryEvent.Tags.Add("username", user); } var id = await client.CaptureAsync(sentryEvent).ConfigureAwait(false); if (id != null && !context.Response.HasStarted) { context.Response.Headers.TryAdd("X-Sentry-Id", id); } throw; } }); }
public SentryEvent Process(SentryEvent @event) { // Here you can modify the event as you need if (@event.Level > SentryLevel.Info) { @event.AddBreadcrumb("Processed by " + nameof(SomeEventProcessor)); @event.User = new User { Username = Environment.UserName }; @event.ServerName = Environment.MachineName; } return(@event); }
public void Process_NetFxInstallationsKeyExist_UnchangedSentryEvent() { Skip.If(Runtime.Current.IsMono(), "Mono not supported."); //Arrange var @event = new SentryEvent(); var sut = _fixture.GetSut(); var userBlob = "user blob"; @event.Contexts[NetFxInstallationsEventProcessor.NetFxInstallationsKey] = userBlob; //Act _ = sut.Process(@event); //Assert Assert.Equal(userBlob, @event.Contexts[NetFxInstallationsEventProcessor.NetFxInstallationsKey]); }
public void Capture(Exception exception, ErrorLevel errorLevel = ErrorLevel.Error, string message = "") { if (!CommonRegistryConfigurations.IsErrorTrackingEnabled(VisualStudioVersion)) { return; } var sentryEvent = new SentryEvent(exception) { Message = message, Level = errorLevel }; sentryEvent.Tags.Add("Visual Studio Version", VisualStudioVersion); _ravenClient.Capture(sentryEvent); }
internal SentryEvent?PrepareEvent(SentryEvent evt, Scope?scope = null) { try { var currentScope = ScopeManager.GetCurrent(); var actualScope = scope ?? currentScope.Key; if (currentScope.Value is SentryClient c) { return(c.PrepareEvent(evt, actualScope)); } } catch (Exception e) { _options.DiagnosticLogger?.LogError("Failure to capture event: {0}", e, evt.EventId); } return(null); }
public void Process_SecondEventWithException_ReturnsNull() { var duplicate = new Exception(); var first = new SentryEvent { Exception = duplicate }; var second = new SentryEvent { Exception = duplicate }; _ = _sut.Process(first); var actual = _sut.Process(second); Assert.Null(actual); }
/// <summary> /// Logs the specified fatal error message. /// </summary> /// <param name="Type">The type.</param> /// <param name="Message">The message.</param> public static void Fatal(Type Type, string Message) { Debug.WriteLine("[ FATAL ] " + Type.Name.Pad() + " : " + Message); if (Sentry.Initialized) { var SentryEvent = new SentryEvent(Message) { Level = ErrorLevel.Fatal }; SentryEvent.Tags.Add("className", Type.Name); SentryEvent.Tags.Add("projectName", Type.Assembly.GetName().Name); Sentry.Raven.CaptureAsync(SentryEvent); } }
public void Process(Exception exception, SentryEvent sentryEvent) { Debug.Assert(sentryEvent != null); _options.DiagnosticLogger?.LogDebug("Running processor on exception: {0}", exception.Message); if (exception != null) { var sentryExceptions = CreateSentryException(exception) // Otherwise realization happens on the worker thread before sending event. .ToList(); MoveExceptionExtrasToEvent(sentryEvent, sentryExceptions); sentryEvent.SentryExceptions = sentryExceptions; } }
public void Process_AggregateExceptionDupe_ReturnsNull() { var duplicate = new Exception(); var first = new SentryEvent { Exception = new AggregateException(duplicate) }; var second = new SentryEvent { Exception = duplicate }; _ = _sut.Process(first); var actual = _sut.Process(second); Assert.Null(actual); }
public static void QueueBobsBuddyTerminalCase(TestInput testInput, TestOutput output, string result, int turn, List <string> debugLog, Region region) { if (BobsBuddyEventsSent >= MaxBobsBuddyEvents) { return; } if (!Helper.IsSigned) { return; } // Clean up data testInput.RemoveSelfReferencesFromMinions(); output.ClearListsForReporting(); //ignoring for some temporary debugging var msg = new SentryMessage($"BobsBuddy {BobsBuddyUtils.VersionString}: Incorrect Terminal Case: {result}"); var data = new BobsBuddyData() { ShortId = "", Turn = turn, Result = result, ThreadCount = BobsBuddyInvoker.ThreadCount, Iterations = output.simulationCount, ExitCondition = output.myExitCondition.ToString(), Input = testInput, Output = output, Log = ReverseAndClone(debugLog), Region = region, CanRemoveLichKing = BobsBuddyInvoker.CanRemoveLichKing }; var bbEvent = new SentryEvent(msg) { Level = ErrorLevel.Warning, Extra = data, }; bbEvent.Tags.Add("region", data.Region.ToString()); bbEvent.Fingerprint.Add(result); bbEvent.Fingerprint.Add(BobsBuddyUtils.VersionString); BobsBuddyEvents.Enqueue(bbEvent); }