Sentry异常日志监控-Java接入

Java 使用Sentry监控后台日志

1.0 平时怎么查看异常日志的?

大多时候查看日志都是通过查看日志文件,或者在命令行通过命令查看,这样是不是很不方便?是真的很不方便!!!
那么有没有什么工具可以方便的进行日志查看和管理呢?当然有!!!

2.0 sentry 日志监控

Sentry 是一个开源的实时错误报告工具,支持 web 前后端、移动应用以及游戏,支持 Python、OC、Java、Go、Node、Django、RoR 等主流编程语言和框架 ,还提供了 GitHub、Slack、Trello 等常见开发工具的集成。
Sentry异常日志监控-Java接入_第1张图片
应用越做越复杂,输出日志五花八门,有print的,有写stdout的,有写stderr的, 有写logging的,也有自定义xxx.log的。那么这将导致平台应用日志分布在各个地方,无法统一管理。而且可能用的还不止一种开发语言,想规范和统一日志不是一件容易的事。

Sentry是一个集中式日志管理系统。它具备以下优点:

  • 多项目,多用户
  • 界面友好
  • 可以配置异常出发规则,例如发送邮件
  • 支持主流语言接口

3.0本地安装和部署

Sentry 官方提供免费版和收费版的服务,如果不想搭建本地服务的话直接用官方服务好了。Sentry是个开源的工具可以自行搭建(推荐使用Docker搭建),具体搭建过程就不写了,自行百度即可迅速完成.搭建完成后即可登陆对应的日志管理页面,新建属于自己的项目,可以看到,支持各种语言的项目.
Sentry异常日志监控-Java接入_第2张图片Sentry异常日志监控-Java接入_第3张图片

4.0Java 项目接入Sentry监控异常日志

  1. 创建一个Java 项目
    Sentry异常日志监控-Java接入_第4张图片

  2. 找到项目对应的dsn
    DSN(Data Source Name)是Sentry 管理项目需要的PROJECT_ID,每个应用都需要对应一个 PROJECT_ID,以及用于身份认证的 PUBLIC_KEY 和 SECRET_KEY。由此组成一个这样的 DSN:
    {PROTOCOL}/{PUBLIC_KEY}:{SECRET_KEY}@{HOST}/{PATH}{PROJECT_ID}
    PROTOCOL 通常会是 http 或者 https,HOST 为 Sentry 服务的主机名和端口,PATH 通常为空。
    在你登入Sentry后台之后,你可以新建一个项目,之后就可以得到类似于下面这样一个DSN。
    Sentry异常日志监控-Java接入_第5张图片

有了DSN以后,你就可以在客户端中将错误日志上传到Sentry了。
3. 配置自己的客户端
3.1 引入依赖

 <!--sentry 日志监控依赖-->
        
            io.sentry
            sentry
            1.7.23
        

3.2 把dsn 写入配置文件,这里我使用的是 sentry.properties 配置文件,将刚才的dsn 配置进去

dsn=http://[email protected]:9000/3

3.3 编写相应的客户端代码,这里可以给到一个例子

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);
        }
    }
}

4.运行程序,查看管理端是否有异常监控Sentry异常日志监控-Java接入_第6张图片
Sentry异常日志监控-Java接入_第7张图片
5. 以上只是捕获单个异常,实际项目中需要所有异常都监控的话,需要根据实际项目代码,在全局异常捕获中或者自定义异常中对应的客户端连接代码,因为每个项目不一样,需要自己根据实际编写,这里就不罗列了.

你可能感兴趣的:(java)