io.sentry.Sentry Java Examples

The following examples show how to use io.sentry.Sentry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SentryUtils.java    From andesite-node with MIT License 6 votes vote down vote up
static void setup(Config config) {
    var client = Sentry.init(config.getString("sentry.dsn"));
    client.setRelease(Version.VERSION);
    client.setTags(parseTags(config.getStringList("sentry.tags")));
    SentryUtils.client = client;
    var loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    var root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
    
    var sentryAppender = (SentryAppender) root.getAppender(SENTRY_APPENDER_NAME);
    if(sentryAppender == null) {
        sentryAppender = new SentryAppender();
        sentryAppender.setName(SENTRY_APPENDER_NAME);
        sentryAppender.start();
        
        var warningsOrAboveFilter = new ThresholdFilter();
        warningsOrAboveFilter.setLevel(config.getString("sentry.log-level").toUpperCase());
        warningsOrAboveFilter.start();
        sentryAppender.addFilter(warningsOrAboveFilter);
        
        sentryAppender.setContext(loggerContext);
        root.addAppender(sentryAppender);
    }
}
 
Example #2
Source File: YoutubeApiPlaylistLoader.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public AudioPlaylist load(HttpInterface httpInterface, String playlistId, String selectedVideoId, Function<AudioTrackInfo, AudioTrack> trackFactory) {
    try {
        final YoutubePlaylistMetadata firstPage = getPlaylistPageById(playlistId, this.apiKey, null, true);

        if (firstPage == null) {
            throw new FriendlyException("This playlist does not exist", COMMON, null);
        }

        return buildPlaylist(firstPage, playlistId, selectedVideoId, trackFactory);
    }
    catch (IOException e) {
        Sentry.capture(e);

        throw ExceptionTools.wrapUnfriendlyExceptions(e);
    }
}
 
Example #3
Source File: DogCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void execute(@Nonnull CommandContext ctx) {
    final String base = "https://random.dog/";
    final GuildMessageReceivedEvent event = ctx.getEvent();
    try {
        WebUtils.ins.getText(base + "woof").async((it) -> {
            final String finalS = base + it;

            if (finalS.contains(".mp4")) {
                sendEmbed(event, EmbedUtils.embedField("A video", "[Click for video](" + finalS + ")"));
            } else {
                sendEmbed(event, EmbedUtils.embedImage(finalS));
            }
        });

    }
    catch (Exception e) {
        //e.printStackTrace();
        sendEmbed(event, EmbedUtils.embedMessage("**[OOPS]** Something broke, blame duncte \n(" + e.toString() + ")"));
        Sentry.capture(e);
    }

}
 
Example #4
Source File: YodaSpeakCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void execute(@Nonnull CommandContext ctx) {
    final GuildMessageReceivedEvent event = ctx.getEvent();

    try {
        final QueryBuilder builder = new QueryBuilder()
            .append("yoda")
            .append("sentence", ctx.getArgsDisplay());
        final JsonNode response = ctx.getApis().executeDefaultGetRequest(builder.build(), false);

        logger.debug("Yoda response: " + response);

        if (!response.get("success").asBoolean()) {
            sendMsg(event, "Could not connect to yoda service, try again in a few hours");
            return;
        }

        final String yoda = ctx.getRandom().nextInt(2) == 1 ? "<:yoda:578198258351079438> " : "<:BABY_YODA:670269491736870972> ";

        sendMsg(event, yoda + response.get("data").asText());
    }
    catch (Exception e) {
        Sentry.capture(e);
        sendMsg(event, "Could not connect to yoda service, try again in a few hours");
    }
}
 
Example #5
Source File: Reporter.java    From KaellyBot with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Rejette une exception dans un salon discord. Politique du "posté uniquement une fois"
 * @param exception Exception à rejeter
 * @param guild Guilde d'origine de l'erreur
 * @param channel Salon d'origine de l'erreur
 * @param user Auteur du message d'origine de l'erreur
 * @param message Contenu du message à l'origine de l'erreur
 */
public void send(Exception exception, Guild guild, Channel channel, User user, discord4j.core.object.entity.Message message){
    try {
        Sentry.getContext().clearTags();
        if (guild != null)
            Sentry.getContext().addTag(GUILD, guild.getId().asString() + " - " + guild.getName());
        if (channel != null)
            Sentry.getContext().addTag(CHANNEL, channel.getId().asString() + " - " + channel.getId());
        if (user != null)
            Sentry.getContext().addTag(USER, user.getId().asString() + " - " + user.getUsername());
        if (message != null)
            Sentry.getContext().addTag(MESSAGE, message.getContent().orElse(""));

        Sentry.capture(exception);

    } catch(Exception e){
        Sentry.capture(exception);
        LOG.error("report", exception);
        Sentry.capture(e);
        LOG.error("report", e);
    }
}
 
Example #6
Source File: SentryHandlerValueFactory.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public RuntimeValue<Optional<Handler>> create(final SentryConfig config) {
    final SentryConfigProvider provider = new SentryConfigProvider(config);
    final Lookup lookup = new Lookup(provider, provider);

    if (!config.enable) {
        // Disable Sentry
        Sentry.init(SentryOptions.from(lookup, Dsn.DEFAULT_DSN));
        return new RuntimeValue<>(Optional.empty());
    }
    if (!config.dsn.isPresent()) {
        throw new ConfigurationException(
                "Configuration key \"quarkus.log.sentry.dsn\" is required when Sentry is enabled, but its value is empty/missing");
    }
    if (!config.inAppPackages.isPresent()) {
        LOG.warn(
                "No 'quarkus.sentry.in-app-packages' was configured, this option is highly recommended as it affects stacktrace grouping and display on Sentry. See https://quarkus.io/guides/logging-sentry#in-app-packages");
    }

    // Init Sentry
    Sentry.init(SentryOptions.from(lookup, config.dsn.get()));
    SentryHandler handler = new SentryHandler();
    handler.setLevel(config.level);
    return new RuntimeValue<>(Optional.of(handler));
}
 
Example #7
Source File: CommandManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private void runCustomCommand(ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) {
    final CustomCommand cc = (CustomCommand) cmd;

    if (cc.getGuildId() != event.getGuild().getIdLong()) {
        return;
    }

    try {
        MDC.put("command.custom.message", cc.getMessage());

        final Parser parser = CommandUtils.getParser(new CommandContext(invoke, args, event, variables));

        final String message = parser.parse(cc.getMessage());
        final MessageBuilder messageBuilder = new MessageBuilder();
        final DataObject object = parser.get("embed");

        if (!message.isEmpty()) {
            messageBuilder.setContent("\u200B" + message);
        }

        if (object != null) {
            final JDAImpl jda = (JDAImpl) event.getJDA();
            final MessageEmbed embed = jda.getEntityBuilder().createMessageEmbed(object);

            messageBuilder.setEmbed(embed);
        }

        if (!messageBuilder.isEmpty()) {
            sendMsg(event, messageBuilder.build());
        }


        parser.clear();
    }
    catch (Exception e) {
        sendMsg(event, "Error with parsing custom command: " + e.getMessage());
        Sentry.capture(e);
    }
}
 
Example #8
Source File: SentryHelper.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void captureException(String message, Throwable t, Class<?> clazz) {
    EventBuilder eventBuilder = new EventBuilder()
            .withMessage(message)
            .withLevel(Event.Level.ERROR)
            .withLogger(clazz.getName())
            .withSentryInterface(new ExceptionInterface(t));
    Sentry.capture(eventBuilder);
}
 
Example #9
Source File: TrackScheduler.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
private void onStop() {
    //stop the track.
    LavalinkPlayer lavalinkPlayer = getAudioPlayer().getPlayer();
    if (lavalinkPlayer.getPlayingTrack() != null)
        lavalinkPlayer.stopTrack();

    getVoteStop().clear();
    getVoteSkips().clear();

    Guild g = getGuild();
    if (g == null) {
        //Why?
        this.getAudioPlayer().destroy();
        return;
    }

    boolean premium = MantaroData.db().getGuild(g).isPremium();
    try {
        TextChannel ch = getRequestedTextChannel();
        if (ch != null && ch.canTalk()) {
            ch.sendMessageFormat(
                    language.get("commands.music_general.queue_finished"),
                    EmoteReference.MEGA, premium ? "" :
                            String.format(language.get("commands.music_general.premium_beg"), EmoteReference.HEART)
            ).queue(message -> message.delete().queueAfter(30, TimeUnit.SECONDS));
        }
    } catch (Exception e) {
        Sentry.capture(e);
    }

    requestedChannel = 0;
    errorCount = 0;
    //If not set to null, those two objects will always be in scope and dangle around in the heap forever.
    //Some AudioTrack objects were of almost 500kb of size, I guess 100k of those can cause a meme.
    currentTrack = null;
    previousTrack = null;

    //Disconnect this audio player.
    this.getAudioPlayer().disconnect();
}
 
Example #10
Source File: SentryHelper.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void captureMessage(String message, Class<?> clazz) {
    EventBuilder eventBuilder = new EventBuilder()
            .withMessage(message)
            .withLevel(Event.Level.INFO)
            .withLogger(clazz.getName());

    Sentry.capture(eventBuilder);
}
 
Example #11
Source File: Entrance.java    From jare with MIT License 5 votes vote down vote up
/**
 * Main entry point.
 * @param args Arguments
 * @throws IOException If fails
 */
public static void main(final String... args) throws IOException {
    Sentry.init(Manifests.read("Jare-SentryDsn"));
    final Base base = new CdBase(new DyBase());
    new Logs(
        base,
        new Region.Simple(
            Manifests.read("Jare-S3Key"),
            Manifests.read("Jare-S3Secret")
        ).bucket("logs.jare.io")
    );
    new FtCli(new TkApp(base), args).start(Exit.NEVER);
}
 
Example #12
Source File: TkAppFallback.java    From jare with MIT License 5 votes vote down vote up
/**
 * Authenticated.
 * @param take Takes
 * @return Authenticated takes
 */
private static Take make(final Take take) {
    return new TkFallback(
        take,
        new FbChain(
            new FbStatus(
                HttpURLConnection.HTTP_NOT_FOUND,
                new RsWithStatus(
                    new RsText("Page not found"),
                    HttpURLConnection.HTTP_NOT_FOUND
                )
            ),
            new FbStatus(
                HttpURLConnection.HTTP_BAD_REQUEST,
                new RsWithStatus(
                    new RsText("Bad request"),
                    HttpURLConnection.HTTP_BAD_REQUEST
                )
            ),
            req -> {
                Sentry.capture(req.throwable());
                return new Opt.Empty<>();
            },
            req -> new Opt.Single<>(TkAppFallback.fatal(req))
        )
    );
}
 
Example #13
Source File: SentryHelper.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void captureExceptionContext(String message, Throwable t, Class<?> clazz, String user) {
    final Context context = Sentry.getContext();
    context.setUser(new UserBuilder().setUsername(user).build());
    EventBuilder eventBuilder = new EventBuilder()
            .withMessage(message)
            .withLevel(Event.Level.ERROR)
            .withLogger(clazz.getName())
            .withSentryInterface(new ExceptionInterface(t));
    Sentry.capture(eventBuilder);
    Sentry.clearContext();
}
 
Example #14
Source File: TkApp.java    From jpeek with MIT License 5 votes vote down vote up
/**
 * Main Java entry point.
 * @param args Command line args
 * @throws IOException If fails
 */
public static void main(final String... args) throws IOException {
    Sentry.init(
        new PropertiesOf(
            new ResourceOf(
                "org/jpeek/jpeek.properties"
            )
        ).value().getProperty("org.jpeek.sentry")
    );
    new FtCli(
        new TkApp(Files.createTempDirectory("jpeek")),
        args
    ).start(Exit.NEVER);
}
 
Example #15
Source File: PerspectiveApi.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public static float checkSwearFilter(String text, String channelId, String apiKey, ProfanityFilterType filterType, ObjectMapper mapper) {
    if (text.isEmpty()) {
        return 0f;
    }

    try {
        final JsonNode json = makeRequest(text, channelId, apiKey, filterType, mapper);

        if (json.has("error")) {
            final String error = json.get("error").get("message").asText();

            if ("Unable to detect language.".equals(error)) {
                return 0f;
            }

            throw new HttpException("Error while handling perspective api request: " + json);
        }

        final JsonNode score = json.get("attributeScores")
            .get(filterType.getType())
            .get("summaryScore");

        return Float.parseFloat(score.get("value").asText());
    }
    catch (Exception e) {
        Sentry.capture(e);
        e.printStackTrace();

        return 0f;
    }
}
 
Example #16
Source File: AirUtils.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void loadGuildMembers(Guild guild) {
    try {
        guild.retrieveMembers().get();
    }
    catch (InterruptedException | ExecutionException e) {
        Sentry.capture(e);
    }
}
 
Example #17
Source File: SentryHelper.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void captureMessageContext(String message, Class<?> clazz, String user) {
    final Context context = Sentry.getContext();
    context.setUser(new UserBuilder().setUsername(user).build());
    EventBuilder eventBuilder = new EventBuilder()
            .withMessage(message)
            .withLevel(Event.Level.INFO)
            .withLogger(clazz.getName());

    Sentry.capture(eventBuilder);
    Sentry.clearContext();
}
 
Example #18
Source File: EventManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void handle(@Nonnull GenericEvent event) {
    final JDA.ShardInfo shardInfo = event.getJDA().getShardInfo();

    if (shouldFakeBlock) {
        //noinspection ConstantConditions
        if (shardInfo == null) {
            logger.warn(TextColor.RED + "Shard booting up (Event {})." + TextColor.RESET, event.getClass().getSimpleName());
            return;
        }

        if (restartingShard == -1 || restartingShard == shardInfo.getShardId()) {
            return;
        }
    }

    for (final EventListener listener : this.listeners) {
        try {
            listener.onEvent(event);
        }
        catch (Throwable thr) {
            Sentry.capture(thr);

            logger.error("Error while handling event {}({}); {}",
                event.getClass().getName(),
                listener.getClass().getSimpleName(),
                thr.getLocalizedMessage());
            logger.error("", thr);
        }
    }
}
 
Example #19
Source File: SentryHelper.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void captureMessageErrorContext(String message, Class<?> clazz, String user) {
    final Context context = Sentry.getContext();
    context.setUser(new UserBuilder().setUsername(user).build());
    EventBuilder eventBuilder = new EventBuilder()
            .withMessage(message)
            .withLevel(Event.Level.ERROR)
            .withLogger(clazz.getName());

    Sentry.capture(eventBuilder);
    Sentry.clearContext();
}
 
Example #20
Source File: SentryLoggerCustomTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void sentryLoggerCustomTest() {
    final SentryHandler sentryHandler = getSentryHandler();
    assertThat(sentryHandler).isNotNull();
    assertThat(sentryHandler.getLevel()).isEqualTo(org.jboss.logmanager.Level.TRACE);
    assertThat(FrameCache.shouldCacheThrowable(new IllegalStateException("Test frame"), 1)).isTrue();
    assertThat(Sentry.getStoredClient()).isNotNull();
    assertThat(Sentry.isInitialized()).isTrue();
}
 
Example #21
Source File: CommandManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public void dispatchCommand(@Nonnull ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) {
    this.commandThread.submit(() -> {
        MDC.put("command.invoke", invoke);
        MDC.put("command.args", args.toString());
        MDC.put("user.tag", event.getAuthor().getAsTag());
        MDC.put("user.id", event.getAuthor().getId());
        MDC.put("guild", event.getGuild().toString());
        setJDAContext(event.getJDA());

        final TextChannel channel = event.getChannel();

        if (!channel.canTalk()) {
            return;
        }

        // Suppress errors from when we can't type in the channel
        channel.sendTyping().queue(null, (t) -> {});

        try {
            if (!cmd.isCustom()) {
                runNormalCommand(cmd, invoke, args, event);
            } else {
                runCustomCommand(cmd, invoke, args, event);
            }
        }
        catch (Throwable ex) {
            Sentry.capture(ex);
            ex.printStackTrace();
            sendMsg(event, "Something went wrong whilst executing the command, my developers have been informed of this\n" + ex.getMessage());
        }
    });
}
 
Example #22
Source File: SentryHelper.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void breadcrumbContext(String breadcrumb, String user) {
    final Context context = Sentry.getContext();
    context.setUser(new UserBuilder().setUsername(user).build());
    context.recordBreadcrumb(
            new BreadcrumbBuilder().setMessage(breadcrumb).build()
    );
    Sentry.clearContext();
}
 
Example #23
Source File: ServerLogger.java    From weMessage with GNU Affero General Public License v3.0 5 votes vote down vote up
static void setServerHook(MessageServer server, ServerConfiguration serverConfiguration){
    try {
        if (USE_SENTRY && serverConfiguration.getConfigJSON().getConfig().getSendCrashReports()) {
            Sentry.init(new SentryConfig(weMessage.SENTRY_DSN, weMessage.WEMESSAGE_VERSION, "production").build());
            Sentry.getStoredClient().addBuilderHelper(new SentryEventHelper());

            isSentryInitialized = true;
        }
    } catch (Exception ex){
        isSentryInitialized = false;
    }

    messageServer = server;
}
 
Example #24
Source File: ServerLogger.java    From weMessage with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void logToSentry(Level level, String tag, String message, Exception ex){
    if (!isSentryInitialized) return;

    Long previousTime = lastSentryExecution;
    long currentTimestamp = System.currentTimeMillis();

    lastSentryExecution = currentTimestamp;

    if (previousTime == null || (currentTimestamp - previousTime > MINIMUM_INTERVAL)){
        EventBuilder eventBuilder = new EventBuilder();

        if (level != null){
            eventBuilder.withLevel(level.sentryLevel());
        }

        if (!StringUtils.isEmpty(tag)){
            eventBuilder.withLogger(tag);
        }

        if (!StringUtils.isEmpty(message)){
            eventBuilder.withMessage(message);
        }

        if (ex != null) {
            eventBuilder.withSentryInterface(new ExceptionInterface(ex));
        }

        Sentry.capture(eventBuilder);
    }
}
 
Example #25
Source File: SentryConfiguration.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty("SENTRY_DSN") // only if environment variable exists
public HandlerExceptionResolver sentryExceptionResolver() {
    // Recipe FROM: https://github.com/getsentry/sentry-java/issues/575
    Sentry.getStoredClient().addShouldSendEventCallback(event ->
            event.getSentryInterfaces().values().stream()
                    .filter(ExceptionInterface.class::isInstance)
                    .map(ExceptionInterface.class::cast)
                    .map(ExceptionInterface::getExceptions)
                    .flatMap(Collection::stream)
                    .noneMatch(sentryException ->
                            Arrays.stream(ignoredExceptions).anyMatch(ignoredException -> sentryException.getExceptionClassName().equals(ignoredException))
                    ));
    Sentry.getStoredClient().addBuilderHelper(eventBuilder -> {
        HttpServletRequest request = SentryServletRequestListener.getServletRequest();
        if (request == null) {
            return;
        }
        eventBuilder.withTag("method", request.getMethod());
        eventBuilder.withTag("application", extractApplication(request.getRequestURI()));
        eventBuilder.withTag("uri", defaultString(getMatchingPattern(request)));
        eventBuilder.withTag("query", defaultString(request.getQueryString()));
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        eventBuilder.withSentryInterface(new UserInterface(null, authentication.getName(),
                remoteAddressResolver.getRemoteAddress(request), null), true);
    });
    log.info("Creating a SentryExceptionResolver as HandlerExceptionResolver - Ignored exceptions: {}", ignoredExceptions);
    return new SentryExceptionResolver();
}
 
Example #26
Source File: SentryConfiguration.java    From Lavalink with MIT License 5 votes vote down vote up
public void turnOn(String dsn, Map<String, String> tags) {
    log.info("Turning on sentry");
    SentryClient sentryClient = Sentry.init(dsn);

    if (tags != null) {
        tags.forEach(sentryClient::addTag);
    }

    // set the git commit hash this was build on as the release
    Properties gitProps = new Properties();
    try {
        //noinspection ConstantConditions
        gitProps.load(Launcher.class.getClassLoader().getResourceAsStream("git.properties"));
    } catch (NullPointerException | IOException e) {
        log.error("Failed to load git repo information", e);
    }

    String commitHash = gitProps.getProperty("git.commit.id");
    if (commitHash != null && !commitHash.isEmpty()) {
        log.info("Setting sentry release to commit hash {}", commitHash);
        sentryClient.setRelease(commitHash);
    } else {
        log.warn("No git commit hash found to set up sentry release");
    }

    getSentryLogbackAppender().start();
}
 
Example #27
Source File: SentryConfiguration.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
@Autowired
public SentryConfiguration(UserService userService, ModelMapper modelMapper) {
    EventBuilderHelper myEventBuilderHelper = eventBuilder -> {
        UserContext userContext = userService.getLoggedInUser()
                .flatMap(user -> Optional.of(modelMapper.map(user, UserContext.class)))
                .orElse(UNAUTHORIZED);

        eventBuilder.withExtra("user", userContext);
    };

    Sentry.getStoredClient().addBuilderHelper(myEventBuilderHelper);
}
 
Example #28
Source File: SentryLoggerReleaseOptionTests.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void sentryLoggerEnvironmentOptionTest() {
    final SentryHandler sentryHandler = getSentryHandler();
    assertThat(sentryHandler).isNotNull();
    assertThat(Sentry.getStoredClient()).isNotNull();
    assertThat(Sentry.getStoredClient().getRelease()).isEqualTo("releaseABC");
    assertThat(Sentry.isInitialized()).isTrue();
}
 
Example #29
Source File: SentryLoggerTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void sentryLoggerDefaultTest() {
    final SentryHandler sentryHandler = getSentryHandler();
    assertThat(sentryHandler).isNotNull();
    assertThat(sentryHandler.getLevel()).isEqualTo(org.jboss.logmanager.Level.WARN);
    assertThat(FrameCache.shouldCacheThrowable(new IllegalStateException("Test frame"), 1)).isFalse();
    assertThat(Sentry.getStoredClient()).isNotNull();
    assertThat(Sentry.isInitialized()).isTrue();
}
 
Example #30
Source File: SentryLoggerDisabledTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void sentryLoggerDisabledTest() {
    final SentryHandler sentryHandler = getSentryHandler();
    assertThat(sentryHandler).isNull();
    assertThat(Sentry.getStoredClient()).isNotNull();
    assertThat(Sentry.isInitialized()).isTrue();
}