public async Task Invoke(IDictionary <string, object> environment) { using (SentrySdk.PushScope()) { SentrySdk.ConfigureScope(scope => { // Gets called if an event is sent out within this request. // By a logger.LogError or FirstChanceException scope.AddEventProcessor(@event => { ApplyContext(@event, environment); return(@event); }); }); try { await _next(environment); } catch (Exception ex) { // An exception thrown in the ExceptionHandler will end up here. var evt = new SentryEvent(ex); ApplyContext(evt, environment); SentrySdk.CaptureEvent(evt); throw; } } }
private async Task HandleError <T>(IEventHandler <T> handler, T evt, ILifetimeScope serviceScope, Exception exc) where T : IGatewayEvent { _metrics.Measure.Meter.Mark(BotMetrics.BotErrors, exc.GetType().FullName); var ourUserId = await _cache.GetOwnUser(); // Make this beforehand so we can access the event ID for logging var sentryEvent = new SentryEvent(exc); // If the event is us responding to our own error messages, don't bother logging if (evt is MessageCreateEvent mc && mc.Author.Id == ourUserId) { return; } var shouldReport = exc.IsOurProblem(); if (shouldReport) { // only log exceptions if they're our problem _logger.Error(exc, "Exception in event handler: {SentryEventId}", sentryEvent.EventId); // Report error to Sentry // This will just no-op if there's no URL set var sentryScope = serviceScope.Resolve <Scope>(); // Add some specific info about Discord error responses, as a breadcrumb // TODO: headers to dict // if (exc is BadRequestException bre) // sentryScope.AddBreadcrumb(bre.Response, "response.error", data: new Dictionary<string, string>(bre.Response.Headers)); // if (exc is NotFoundException nfe) // sentryScope.AddBreadcrumb(nfe.Response, "response.error", data: new Dictionary<string, string>(nfe.Response.Headers)); // if (exc is UnauthorizedException ue) // sentryScope.AddBreadcrumb(ue.Response, "response.error", data: new Dictionary<string, string>(ue.Response.Headers)); SentrySdk.CaptureEvent(sentryEvent, sentryScope); // most of these errors aren't useful... if (_config.DisableErrorReporting) { return; } // Once we've sent it to Sentry, report it to the user (if we have permission to) var reportChannel = handler.ErrorChannelFor(evt, ourUserId); if (reportChannel == null) { return; } var botPerms = await _cache.PermissionsIn(reportChannel.Value); if (botPerms.HasFlag(PermissionSet.SendMessages | PermissionSet.EmbedLinks)) { await _errorMessageService.SendErrorMessage(reportChannel.Value, sentryEvent.EventId.ToString()); } } }
/// <summary> /// Sends a report to Sentry only (no log, no toast, etc.). /// Does not send to Sentry if ApplicationUpdateSupport.IsDev is true. /// Fails silently. /// </summary> /// <param name="message">The message to send with the report</param> /// <param name="fullDetailedMessage">An optional message which can be added to the Sentry report</param> public static void ReportSentryOnly(string message, string fullDetailedMessage = null) { if (ApplicationUpdateSupport.IsDev) { Debug.WriteLine("Developer, we though you might want to know that ReportSentryOnly() was called. Ignore if you like."); Debug.Indent(); Debug.WriteLine(message); Debug.WriteLine(fullDetailedMessage); Debug.Unindent(); return; } try { var evt = new SentryEvent { Message = message }; if (!string.IsNullOrWhiteSpace(fullDetailedMessage)) { evt.SetExtra("fullDetailedMessage", fullDetailedMessage); } evt.SetExtra("stackTrace", new StackTrace().ToString()); SentrySdk.CaptureEvent(evt); } catch (Exception err) { // will only "do something" if we're testing reporting and have thus turned off checking for dev Debug.Fail(err.Message); } }
private static async Task App() { SentrySdk.ConfigureScope(scope => scope.AddTag("Initial scope data.")); SentrySdk.WithClientAndScope((client, scope) => { // Create heavy event stuff var evt = new SentryEvent("Entrypoint event."); scope.AddTag("Some scope change done in the callback"); return(client.CaptureEvent(evt, scope)); }); // TODO: how does it behave with .ConfigureAwait(false); var task = Task.Run(() => { // If no scope is pushed here, it'd be mutating the outer scope SentrySdk.PushScope(); // New scope, clone of the parent // Should it be ConfigureNewScope instead and bundle operations? SentrySdk.ConfigureScope(scope => scope.AddTag("First TPL task adding to scope")); // Simply send event SentrySdk.CaptureEvent(new SentryEvent("First Event from TPL")); }); await task; // here we shouldn't see side-effect from the TPL task SentrySdk.CaptureEvent(new SentryEvent("Final event from main thread")); throw new Exception("Error in the app"); }
public async Task <Usuario> ObterPorCpf(string cpf) { SentrySdk.CaptureEvent(new SentryEvent(new Exception("Teste 1234"))); try { var chaveCache = $"Usuario-{cpf}"; var usuarioCache = await cacheRepositorio.ObterAsync(chaveCache); if (!string.IsNullOrWhiteSpace(usuarioCache)) { return(JsonConvert.DeserializeObject <Usuario>(usuarioCache)); } using var conexao = InstanciarConexao(); conexao.Open(); var usuario = await conexao.FirstOrDefaultAsync <Usuario>(x => !x.Excluido && x.Cpf == cpf); return(usuario); } catch (Exception ex) { SentrySdk.CaptureException(ex); return(null); } }
private void SendTunFallbackEvent() { SentrySdk.CaptureEvent(new SentryEvent { Message = "TUN adapter not found. Adapter changed to TAP.", Level = SentryLevel.Info, }); }
public static void TrackEvent(string @event) { SentrySdk.CaptureEvent(new SentryEvent() { Message = @event, Level = SentryLevel.Info }); Analytics.TrackEvent(@event); }
public static void FatalError(string message, Exception exception) { SentryEvent sentryEvent = new SentryEvent(exception) { Message = message, Level = Sentry.Protocol.SentryLevel.Fatal }; SentrySdk.CaptureEvent(sentryEvent); }
public static void FatalError(string message, Exception exception) { SentryEvent sentryEvent = new SentryEvent(exception) { Message = message, Level = Sentry.Protocol.SentryLevel.Fatal }; sentryEvent.SetTag("HRESULT", exception.HResult.ToString()); SentrySdk.CaptureEvent(sentryEvent); }
private void SendMessage(string message) { if (message == "event") { var @event = new SentryEvent("Event message") { level = "debug" }; SentrySdk.CaptureEvent(@event); } }
private async Task HandleRuntimeError(PKEventHandler eventHandler, Exception exc, Scope scope) { _logger.Error(exc, "Exception in bot event handler"); var evt = new SentryEvent(exc); // Don't blow out our Sentry budget on sporadic not-our-problem erorrs if (exc.IsOurProblem()) SentrySdk.CaptureEvent(evt, scope); // Once we've sent it to Sentry, report it to the user await eventHandler.ReportError(evt, exc); }
private void HandleRuntimeError(Exception e, IServiceProvider services) { var logger = services.GetRequiredService <ILogger>(); var scope = services.GetRequiredService <Scope>(); logger.Error(e, "Exception in bot event handler"); var evt = new SentryEvent(e); SentrySdk.CaptureEvent(evt, scope); Console.Error.WriteLine(e); }
protected override void Write(LogEventInfo logEvent) { if (_unauthorized || !SentryEnabled) { return; } try { SentrySdk.AddBreadcrumb(logEvent.FormattedMessage, logEvent.LoggerName, level: BreadcrumbLevelMap[logEvent.Level]); // don't report non-critical events without exceptions if (!IsSentryMessage(logEvent)) { return; } var fingerPrint = GetFingerPrint(logEvent); if (!_debounce.Allowed(fingerPrint)) { return; } var extras = logEvent.Properties.ToDictionary(x => x.Key.ToString(), x => (object)x.Value.ToString()); extras.Remove("Sentry"); if (logEvent.Exception != null) { foreach (DictionaryEntry data in logEvent.Exception.Data) { extras.Add(data.Key.ToString(), data.Value.ToString()); } } var sentryEvent = new SentryEvent(logEvent.Exception) { Level = LoggingLevelMap[logEvent.Level], Logger = logEvent.LoggerName, Message = logEvent.FormattedMessage }; sentryEvent.SetExtras(extras); sentryEvent.SetFingerprint(fingerPrint); SentrySdk.CaptureEvent(sentryEvent); } catch (Exception e) { OnError(e); } }
public async Task VerificaRegraAlteracaoFrequencia(long registroFrequenciaId, DateTime criadoEm, DateTime alteradoEm, long usuarioAlteracaoId) { int anoAtual = DateTime.Now.Year; // Parametro do sistema de dias para notificacao var qtdDiasParametroString = await repositorioParametrosSistema.ObterValorPorTipoEAno( TipoParametroSistema.QuantidadeDiasNotificarAlteracaoChamadaEfetivada, anoAtual); var parseado = int.TryParse(qtdDiasParametroString, out int qtdDiasParametro); if (!parseado) { SentrySdk.CaptureEvent(new SentryEvent(new Exception($"Não foi encontrado parametro ativo para o tipo 'QuantidadeDiasNotificarAlteracaoChamadaEfetivada' para o ano de {anoAtual}"))); return; } var qtdDiasAlteracao = (alteradoEm.Date - criadoEm.Date).TotalDays; // Verifica se ultrapassou o limite de dias para alteração if (qtdDiasAlteracao < qtdDiasParametro) { return; } var usuariosNotificacao = new List <(Cargo?, Usuario)>(); // Dados da Aula var registroFrequencia = repositorioFrequencia.ObterAulaDaFrequencia(registroFrequenciaId); MeusDadosDto professor = await servicoEOL.ObterMeusDados(registroFrequencia.ProfessorRf); // Gestores var usuarios = BuscaGestoresUe(registroFrequencia.CodigoUe); if (usuarios != null) { usuariosNotificacao.AddRange(usuarios); } // Supervisores usuarios = BuscaSupervisoresUe(registroFrequencia.CodigoUe, usuariosNotificacao.Select(u => u.Item1)); if (usuarios != null) { usuariosNotificacao.AddRange(usuarios); } foreach (var usuario in usuariosNotificacao) { NotificaAlteracaoFrequencia(usuario.Item2, registroFrequencia, professor.Nome); } }
internal NativeExceptionHandler() { AndroidEnvironment.UnhandledExceptionRaiser += (sender, args) => { var exceptionEvent = new SentryEvent(args.Exception); exceptionEvent.SentryExceptions.First().Mechanism = new Mechanism() { Handled = false, Type = "AndroidEnvironment_UnhandledExceptionRaiser" }; SentrySdk.CaptureEvent(exceptionEvent); SentrySdk.FlushAsync(TimeSpan.FromSeconds(10)).Wait(); }; }
private async Task HandleError <T>(IEventHandler <T> handler, T evt, ILifetimeScope serviceScope, Exception exc) where T : DiscordEventArgs { _metrics.Measure.Meter.Mark(BotMetrics.BotErrors, exc.GetType().FullName); // Make this beforehand so we can access the event ID for logging var sentryEvent = new SentryEvent(exc); _logger .ForContext("Elastic", "yes?") .Error(exc, "Exception in event handler: {SentryEventId}", sentryEvent.EventId); // If the event is us responding to our own error messages, don't bother logging if (evt is MessageCreateEventArgs mc && mc.Author.Id == _client.CurrentUser.Id) { return; } var shouldReport = exc.IsOurProblem(); if (shouldReport) { // Report error to Sentry // This will just no-op if there's no URL set var sentryScope = serviceScope.Resolve <Scope>(); // Add some specific info about Discord error responses, as a breadcrumb if (exc is BadRequestException bre) { sentryScope.AddBreadcrumb(bre.WebResponse.Response, "response.error", data: new Dictionary <string, string>(bre.WebResponse.Headers)); } if (exc is NotFoundException nfe) { sentryScope.AddBreadcrumb(nfe.WebResponse.Response, "response.error", data: new Dictionary <string, string>(nfe.WebResponse.Headers)); } if (exc is UnauthorizedException ue) { sentryScope.AddBreadcrumb(ue.WebResponse.Response, "response.error", data: new Dictionary <string, string>(ue.WebResponse.Headers)); } SentrySdk.CaptureEvent(sentryEvent, sentryScope); // Once we've sent it to Sentry, report it to the user (if we have permission to) var reportChannel = handler.ErrorChannelFor(evt); if (reportChannel != null && reportChannel.BotHasAllPermissions(Permissions.SendMessages | Permissions.EmbedLinks)) { await _errorMessageService.SendErrorMessage(reportChannel, sentryEvent.EventId.ToString()); } } }
public static void Error(string message, Exception exception, IEnumerable <KeyValuePair <string, string> > extraTags = null) { SentryEvent sentryEvent = new SentryEvent(exception) { Message = message, Level = Sentry.Protocol.SentryLevel.Error, }; if (extraTags != null) { sentryEvent.SetTags(extraTags); } SentrySdk.CaptureEvent(sentryEvent); }
private void HandleRuntimeError(Exception e, IServiceProvider services) { var logger = services.GetRequiredService <ILogger>(); var scope = services.GetRequiredService <Scope>(); logger.Error(e, "Exception in bot event handler"); var evt = new SentryEvent(e); // Don't blow out our Sentry budget on sporadic not-our-problem erorrs if (e.IsOurProblem()) { SentrySdk.CaptureEvent(evt, scope); } }
private static void ReportError(Exception e) { Trace.WriteLine(""); Trace.WriteLine(e); Trace.WriteLine(""); Trace.WriteLine("エラーだゴメン!(涙"); #if !DEBUG try { SentrySdk.WithScope(scope => { void SetSkinNameTag(string skinName, string scopeTagKindPart) { if (skinName != null) { scope.SetTag($"skin.{scopeTagKindPart}.name", ToSha256InBase64(skinName)); } } var boxDefSkinNameOrFallback = GetCurrentSkinNameOrFallback("box.def", CSkin.GetCurrentBoxDefSkinName); var systemSkinNameOrFallback = GetCurrentSkinNameOrFallback("system", CSkin.GetCurrentSystemSkinName); SetSkinNameTag(boxDefSkinNameOrFallback, "boxdef"); SetSkinNameTag(systemSkinNameOrFallback, "system"); var level = ShouldCaptureAtErrorLevel(e, boxDefSkinNameOrFallback, systemSkinNameOrFallback) ? SentryLevel.Error : SentryLevel.Warning; SentrySdk.CaptureEvent(new SentryEvent(e) { Level = level }); }); } catch (TimeoutException) { Trace.WriteLine("Timeout encountered when attempting to report an error to Sentry"); } catch (Exception exception) { Trace.WriteLine("Unexpected exception encountered when attempting to report an error: " + exception); } #endif }
public IEnumerable <AulasPorTurmaDisciplinaDto> ObterAulasSemRegistroFrequencia(string turmaId, string disciplinaId, TipoNotificacaoFrequencia tipoNotificacao) { var query = @"select a.id, a.professor_rf as professorId, a.data_aula as dataAula, a.quantidade from aula a where not a.excluido and not a.migrado and not exists ( select 1 from notificacao_frequencia n where n.aula_id = a.id and n.tipo = @tipoNotificacao) and not exists ( select 1 from registro_frequencia r where r.aula_id = a.id) and a.data_aula < date(now()) and a.turma_id = @turmaId and a.disciplina_id = @disciplinaId" ; IEnumerable <AulasPorTurmaDisciplinaDto> lista = new List <AulasPorTurmaDisciplinaDto>(); try { lista = database.Conexao.Query <AulasPorTurmaDisciplinaDto>(query, new { turmaId, disciplinaId, tipoNotificacao }); } catch (Exception ex) { SentrySdk.CaptureEvent(new SentryEvent(ex)); SentrySdk.CaptureEvent(new SentryEvent(new NegocioException($"ObterAulasSemRegistroFrequencia - {turmaId} - {disciplinaId}"))); } return(lista); }
private async Task HandleError <T>(IEventHandler <T> handler, T evt, ILifetimeScope serviceScope, Exception exc) where T : DiscordEventArgs { // Make this beforehand so we can access the event ID for logging var sentryEvent = new SentryEvent(exc); _logger.Error(exc, "Exception in bot event handler (Sentry ID: {SentryEventId})", sentryEvent.EventId); var shouldReport = exc.IsOurProblem(); if (shouldReport) { // Report error to Sentry // This will just no-op if there's no URL set var sentryScope = serviceScope.Resolve <Scope>(); // Add some specific info about Discord error responses, as a breadcrumb if (exc is BadRequestException bre) { sentryScope.AddBreadcrumb(bre.WebResponse.Response, "response.error", data: new Dictionary <string, string>(bre.WebResponse.Headers)); } if (exc is NotFoundException nfe) { sentryScope.AddBreadcrumb(nfe.WebResponse.Response, "response.error", data: new Dictionary <string, string>(nfe.WebResponse.Headers)); } if (exc is UnauthorizedException ue) { sentryScope.AddBreadcrumb(ue.WebResponse.Response, "response.error", data: new Dictionary <string, string>(ue.WebResponse.Headers)); } SentrySdk.CaptureEvent(sentryEvent, sentryScope); // Once we've sent it to Sentry, report it to the user (if we have permission to) var reportChannel = handler.ErrorChannelFor(evt); if (reportChannel != null && reportChannel.BotHasAllPermissions(Permissions.SendMessages)) { var eid = sentryEvent.EventId; await reportChannel.SendMessageAsync( $"{Emojis.Error} Internal error occurred. Please join the support server (<https://discord.gg/PczBt78>), and send the developer this ID: `{eid}`\nBe sure to include a description of what you were doing to make the error occur."); } } }
public static void SendEmail(Exception exception) { using (SentrySdk.Init(o => { o.Dsn = new Dsn(ConfigUtils.SentryDsn); })) { var request = GetRequest(); var session = HttpContext.Current.Session; try { var builder = new ExceptionWithDataBuilder(exception, request, session); SentrySdk.CaptureEvent(new SentryEvent(builder.Build())); } catch (Exception e) { // So weird. We need to log it SentrySdk.CaptureException(e); SentrySdk.CaptureException(exception); } } }
static async Task ProposedApi() { SentrySdk.Init(); SentrySdk.ConfigureScope(s => s.AddTag("Some proposed APIs")); // if the goal is avoiding execution of the callback when the SDK is disabled // the simplest API is a delegate to create the event // Async is best if underlying client is doing I/O (writing event to disk or sending via HTTP) var id = await SentrySdk.CaptureEventAsync(async() => { // NOT invoked if the SDK is disabled var dbStuff = await DatabaseQuery(); return(new SentryEvent(dbStuff)); }); Console.WriteLine("Id: " + id); // Blocking alternative (best if using in-memory queue) id = SentrySdk.CaptureEvent(() => new SentryEvent("Nothing async in this callback")); Console.WriteLine("Id: " + id); }
private new void SendMessage(string message) { if (message == "exception") { throw new DivideByZeroException(); } else if (message == "assert") { Assert.AreEqual(message, "not equal"); } else if (message == "message") { SentrySdk.CaptureMessage("this is a message"); } else if (message == "event") { var @event = new SentryEvent("Event message") { level = "debug" }; SentrySdk.CaptureEvent(@event); } }
public override void Handle(ExceptionHandlerContext context) { ExceptionDispatchInfo info = ExceptionDispatchInfo.Capture(context.Exception); // Add any contextual data you want to the event: var @event = new SentryEvent(info.SourceException) { Request = new Request { Method = context.Request.Method.ToString(), Url = context.Request.RequestUri.AbsoluteUri, QueryString = context.Request.Headers.ToString() } }; @event.SetTag("http-version", context.Request.Version.ToString()); SentrySdk.CaptureEvent(@event); // Set the result: context.Result = new InternalServerErrorResult(context.Request); // Or re-throw if you want it to bubble up the middleware chain (Sentry removes duplicate captures) //info.Throw(); }
public void SendCachedLog() { var names = _offlineCacheHelper.GetFileNames(); //TODO: FIX for (int i = 0; i < names.Count /*&& CrossConnectivity.Current.IsConnected*/; i++) { try { var @event = _offlineCacheHelper.GetCache(names[i], _key); if (@event != null) { //Not the best way of doing that because it ll mix with the previous scope SentrySdk.WithScope(scope => { scope.User = @event.User; //TODO: save inside the event // scope.Environment = EnvironmentConfig.AppEnvironment.ToString(); for (int j = 0; j < @event.TagsKeys.Count; j++) { scope.SetTag(@event.TagsKeys[j], @event.TagsValues[j]); } for (int j = 0; j < @event.ExtraKeys.Count; j++) { scope.SetExtra(@event.ExtraKeys[j], @event.ExtraValues[j]); } SentryEvent evento = new SentryEvent(); if (@event.StackModule != null) { List <SentryException> se = new List <SentryException>(); for (int j = 0, k = 0; j < @event.StackModule.Count; j++) { se.Add(new SentryException() { Module = @event.StackModule[j], Type = @event.StackType[j], Value = @event.StackValue[j], ThreadId = 1 }); if (@event.StackFrameTotalPerStack.Count() > 0 && k < @event.StackFrameTotalPerStack[j]) { var stackLast = se.Last(); //get reference stackLast.Stacktrace = new SentryStackTrace(); var listaFrames = new List <SentryStackFrame>(); while (k < @event.StackFrameTotalPerStack[j]) { var frame = new SentryStackFrame() { ContextLine = @event.StackFrameContextLine[k], FileName = @event.StackFrameFileName[k], Function = @event.StackFrameFunction[k], ImageAddress = @event.StackFrameImgAddress[k], InApp = @event.StackFrameInApp[k], InstructionOffset = @event.StackFrameInstOffset[k], LineNumber = (int)@event.StackFrameLineNumb[k], Module = @event.StackFrameModule[k], Package = @event.StackFramePackage[k], }; stackLast.Stacktrace.Frames.Add(frame); k++; } } } evento.SentryExceptions = se; } evento.Platform = "csharp"; evento.Level = @event.Level; evento.Message = @event.Message; //evento.Release = _deviceInfo.GetVersion(); SentrySdk.CaptureEvent(evento); }); _offlineCacheHelper.RemoveLogCache(names[i]); } } catch { //o documento existe, mas houve algum problema no processamento dele, então exclua ele e faça //o parse dos demais _offlineCacheHelper.RemoveLogCache(names[i]); } } }
private static async Task Main() { // When the SDK is disabled, no callback is executed: await SentrySdk.ConfigureScopeAsync(async scope => { // Never executed: // This could be any async I/O operation, like a DB query await Task.Yield(); scope.SetExtra("Key", "Value"); }); // Enable the SDK using (SentrySdk.Init(o => { // Send stack trace for events that were not created from an exception // e.g: CaptureMessage, log.LogDebug, log.LogInformation ... o.AttachStacktrace = true; // Sentry won't consider code from namespace LibraryX.* as part of the app code and will hide it from the stacktrace by default // To see the lines from non `AppCode`, select `Full`. Will include non App code like System.*, Microsoft.* and LibraryX.* o.AddInAppExclude("LibraryX."); // Before excluding all prefixed 'LibraryX.', any stack trace from a type namespaced 'LibraryX.Core' will be considered InApp. o.AddInAppInclude("LibraryX.Core"); // Send personal identifiable information like the username logged on to the computer and machine name o.SendDefaultPii = true; // To enable event sampling, uncomment: // o.SampleRate = 0.5f; // Randomly drop (don't send to Sentry) half of events // Modifications to event before it goes out. Could replace the event altogether o.BeforeSend = @event => { // Drop an event altogether: if (@event.Tags.ContainsKey("SomeTag")) { return(null); } return(@event); }; // Allows inspecting and modifying, returning a new or simply rejecting (returning null) o.BeforeBreadcrumb = crumb => { // Don't add breadcrumbs with message containing: if (crumb.Message?.Contains("bad breadcrumb") == true) { return(null); } return(crumb); }; // Ignore exception by its type: o.AddExceptionFilterForType <XsltCompileException>(); // Configure the background worker which sends events to sentry: // Wait up to 5 seconds before shutdown while there are events to send. o.ShutdownTimeout = TimeSpan.FromSeconds(5); // Enable SDK logging with Debug level o.Debug = true; // To change the verbosity, use: // o.DiagnosticLevel = SentryLevel.Info; // To use a custom logger: // o.DiagnosticLogger = ... // Using a proxy: o.HttpProxy = null; //new WebProxy("https://*****:*****@user{timestamp}.com"; SentrySdk.CaptureUserFeedback(new UserFeedback(eventId, user, email, "this is a sample user feedback")); var error = new Exception("Attempting to send this multiple times"); // Only the first capture will be sent to Sentry for (var i = 0; i < 3; i++) { // The SDK is able to detect duplicate events: // This is useful, for example, when multiple loggers log the same exception. Or exception is re-thrown and recaptured. SentrySdk.CaptureException(error); } var count = 10; for (var i = 0; i < count; i++) { const string msg = "{0} of {1} items we'll wait to flush to Sentry!"; SentrySdk.CaptureEvent(new SentryEvent { Message = new SentryMessage { Message = msg, Formatted = string.Format(msg, i, count) }, Level = SentryLevel.Debug }); } // Console output will show queue being flushed. Task completes then and timeout is never reached (you don't need to wait a day :) await SentrySdk.FlushAsync(TimeSpan.FromDays(1)); // ------------------------- // A custom made client, that could be registered with DI, // would get disposed by the container on app shutdown var evt = new SentryEvent(); evt.Message = "Starting new client"; evt.AddBreadcrumb("Breadcrumb directly to the event"); evt.User.Username = "******"; // Group all events with the following fingerprint: evt.SetFingerprint(new [] { "NewClientDebug" }); evt.Level = SentryLevel.Debug; SentrySdk.CaptureEvent(evt); // Using a different DSN: using (var adminClient = new SentryClient(new SentryOptions { Dsn = AdminDsn })) { // Make believe web framework middleware var middleware = new AdminPartMiddleware(adminClient, null); var request = new { Path = "/admin" }; // made up request middleware.Invoke(request); } // Dispose the client which flushes any queued events SentrySdk.CaptureException( new Exception("Error outside of the admin section: Goes to the default DSN")); } // On Dispose: SDK closed, events queued are flushed/sent to Sentry }
public void CaptureEvent_Instance_NoOp() => SentrySdk.CaptureEvent(new SentryEvent());
private async Task <UserAuthenticationVM> GetAccessToken() { HttpClient httpClient = new HttpClient(); UserLoginVM loginVM = new UserLoginVM() { UserName = "******", Password = "******" }; var url = GetHostAddress(); url.Path = "/api/tokens/create"; var response = await httpClient.PostAsJsonAsync(url.ToString(), loginVM); var responseString = await response.Content.ReadAsStringAsync(); UserAuthenticationVM authModel = null; APIResultVM apiResult = null; try { if (responseString.Contains("Errors", StringComparison.CurrentCultureIgnoreCase)) { apiResult = JsonSerializer.Deserialize <APIResultVM>(responseString); if (apiResult.Errors != null && apiResult.Errors.Any(a => a.ErrorCode == APIStatusCode.ERR02025)) { var user = await _userManager.FindByNameAsync("testuser"); if (user == null) { throw new Exception("GetAccessToken for HealthChecks or UnitTests, is failed, user not found"); } var database = _redis.GetDatabase(); var tokenDataResult = database.StringGet(user.Id.ToString()); if (!tokenDataResult.HasValue) { throw new Exception("GetAccessToken for HealthChecks or UnitTests, is failed, user token data not found"); } TokenCacheVM tokenData = JsonSerializer.Deserialize <TokenCacheVM>(tokenDataResult); return(new UserAuthenticationVM() { TokenData = tokenData, Id = tokenData.Id }); } else { return(default(UserAuthenticationVM)); } } else if (responseString.Contains("UserName", StringComparison.CurrentCultureIgnoreCase)) { authModel = JsonSerializer.Deserialize <UserAuthenticationVM>(responseString); return(authModel); } else { SentrySdk.CaptureEvent(new SentryEvent() { Message = "GetAccessToken for HealthChecks or UnitTests, is failed", Level = Sentry.Protocol.SentryLevel.Error }); return(default(UserAuthenticationVM)); } } catch (System.Exception e) { SentrySdk.CaptureException(e); return(default(UserAuthenticationVM)); } }
public static SentryId CaptureEvent(SentryEvent evt, Scope scope) { using (CreateSdk()) { return(SentrySdk.CaptureEvent(evt, scope)); } }