1. 程式人生 > >Java整合Sentry之使用Sentry

Java整合Sentry之使用Sentry

以下頁面提供了有關如何直接配置和使用Sentry的示例。如果可能,強烈建議您使用提供的整合方式。配置整合後,您還可以使用Sentry的靜態API,如下所示,以便執行記錄麵包屑,設定當前使用者或手動傳送事件等操作。

一、安裝

使用Maven:

<dependency>
    <groupId>io.sentry</groupId>
    <artifactId>sentry</artifactId>
    <version>1.7.10</version>
</dependency>

使用Gradle:

compile 'io.sentry:sentry:1.7.10'

使用SBT:

libraryDependencies += "io.sentry" % "sentry" % "1.7.10"

對於其他依賴管理器,請檢視中央Maven儲存庫。

二、上報錯誤

要手動報告事件,您需要初始化SentryClient。建議您通過Sentry類使用靜態API,但也可以構建和管理自己的SentryClient例項。每種樣式的示例如下所示:

import io.sentry.context.Context;
import io.sentry.event.BreadcrumbBuilder;
import io.sentry.event.UserBuilder;

public class MyClass {
    private static SentryClient sentry;

    public static void main(String... args) {
        /*
         It is recommended that you use the DSN detection system, which
         will check the environment variable "SENTRY_DSN", the Java
         System Property "sentry.dsn", or the "sentry.properties" file
         in your classpath. This makes it easier to provide and adjust
         your DSN without needing to change your code. See the configuration
         page for more information.
         */
        Sentry.init();

        // You can also manually provide the DSN to the ``init`` method.
        String dsn = args[0];
        Sentry.init(dsn);

        /*
         It is possible to go around the static ``Sentry`` API, which means
         you are responsible for making the SentryClient instance available
         to your code.
         */
        sentry = SentryClientFactory.sentryClient();

        MyClass myClass = new MyClass();
        myClass.logWithStaticAPI();
        myClass.logWithInstanceAPI();
    }

    /**
      * An example method that throws an exception.
      */
    void unsafeMethod() {
        throw new UnsupportedOperationException("You shouldn't call this!");
    }

    /**
      * Examples using the (recommended) static API.
      */
    void logWithStaticAPI() {
        // Note that all fields set on the context are optional. Context data is copied onto
        // all future events in the current context (until the context is cleared).

        // Record a breadcrumb in the current context. By default the last 100 breadcrumbs are kept.
        Sentry.getContext().recordBreadcrumb(
            new BreadcrumbBuilder().setMessage("User made an action").build()
        );

        // Set the user in the current context.
        Sentry.getContext().setUser(
            new UserBuilder().setEmail("
[email protected]
").build() ); // Add extra data to future events in this context. Sentry.getContext().addExtra("extra", "thing"); // Add an additional tag to future events in this context. Sentry.getContext().addTag("tagName", "tagValue"); /* This sends a simple event to Sentry using the statically stored instance that was created in the ``main`` method. */ Sentry.capture("This is a test"); try { unsafeMethod(); } catch (Exception e) { // This sends an exception event to Sentry using the statically stored instance // that was created in the ``main`` method. Sentry.capture(e); } } /** * Examples that use the SentryClient instance directly. */ void logWithInstanceAPI() { // Retrieve the current context. Context context = sentry.getContext(); // Record a breadcrumb in the current context. By default the last 100 breadcrumbs are kept. context.recordBreadcrumb(new BreadcrumbBuilder().setMessage("User made an action").build()); // Set the user in the current context. context.setUser(new UserBuilder().setEmail("
[email protected]
").build()); // This sends a simple event to Sentry. sentry.sendMessage("This is a test"); try { unsafeMethod(); } catch (Exception e) { // This sends an exception event to Sentry. sentry.sendException(e); } } }

 三、建立更復雜的事件

import io.sentry.Sentry;
   import io.sentry.event.Event;
   import io.sentry.event.EventBuilder;
   import io.sentry.event.interfaces.ExceptionInterface;

   public class MyClass {
       public static void main(String... args) {
           Sentry.init();
       }

       void unsafeMethod() {
           throw new UnsupportedOperationException("You shouldn't call this!");
       }

       void logSimpleMessage() {
           // This sends an event to Sentry.
           EventBuilder eventBuilder = new EventBuilder()
                           .withMessage("This is a test")
                           .withLevel(Event.Level.INFO)
                           .withLogger(MyClass.class.getName());

           // Note that the *unbuilt* EventBuilder instance is passed in so that
           // EventBuilderHelpers are run to add extra information to your event.
           Sentry.capture(eventBuilder);
       }

       void logException() {
           try {
               unsafeMethod();
           } catch (Exception e) {
               // This sends an exception event to Sentry.
               EventBuilder eventBuilder = new EventBuilder()
                               .withMessage("Exception caught")
                               .withLevel(Event.Level.ERROR)
                               .withLogger(MyClass.class.getName())
                               .withSentryInterface(new ExceptionInterface(e));

               // Note that the *unbuilt* EventBuilder instance is passed in so that
               // EventBuilderHelpers are run to add extra information to your event.
               Sentry.capture(eventBuilder);
           }
       }
}

 四、自動增強事件

您還可以實現一個能夠自動增強傳出事件的EventBuilderHelper。

import io.sentry.Sentry;
import io.sentry.SentryClient;
import io.sentry.event.EventBuilder;
import io.sentry.event.helper.EventBuilderHelper;

public class MyClass {
    public void myMethod() {
        SentryClient client = Sentry.getStoredClient();

        EventBuilderHelper myEventBuilderHelper = new EventBuilderHelper() {
            @Override
            public void helpBuildingEvent(EventBuilder eventBuilder) {
                eventBuilder.withMessage("Overwritten by myEventBuilderHelper!");
            }
        };

        // Add an ``EventBuilderHelper`` to the current client instance. Note that
        // this helper will process *all* future events.
        client.addBuilderHelper(myEventBuilderHelper);

        // Send an event to Sentry. During construction of the event the message
        // body will be overwritten by ``myEventBuilderHelper``.
        Sentry.capture("Hello, world!");
    }
}