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("hello@sentry.io").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("hello@sentry.io").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!");
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 可以很方便地集成 Sentry,以下是集成步骤: 1. 在 `pom.xml` 文件中添加 Sentry 依赖: ```xml <dependency> <groupId>io.sentry</groupId> <artifactId>sentry-spring-boot-starter</artifactId> <version>3.1.0</version> </dependency> ``` 2. 在 `application.properties` 或 `application.yml` 文件中配置 Sentry: ```properties sentry.dsn=YOUR_DSN sentry.release=YOUR_RELEASE_VERSION sentry.environment=YOUR_ENVIRONMENT ``` 其中,`YOUR_DSN` 是你的 Sentry DSN(Data Source Name),`YOUR_RELEASE_VERSION` 是你的应用版本号,`YOUR_ENVIRONMENT` 是你的应用环境(如 `production`、`development` 等)。 3. 创建一个全局异常处理器类,用于捕获异常并发送到 Sentry: ```java import io.sentry.Sentry; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ModelAndView handleException(Exception e) { // 发送异常信息到 Sentry Sentry.captureException(e); // 返回错误页面或其他处理方式 ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("error"); modelAndView.addObject("errorMessage", "An error occurred"); return modelAndView; } } ``` 以上步骤完成后,当应用发生异常时,Sentry 将会自动捕获并发送相应的异常信息。你可以登录 Sentry 平台查看应用的异常报告和性能指标。 希望以上信息对你有帮助!如果你还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值