sentry-logback库通过Appender为Sentry提供Logback支持,该Appender将记录的异常发送给Sentry。配置此集成后,您还可以使用Sentry的静态API(如使用情况页面所示),以便执行记录面包屑,设置当前用户或手动发送事件等操作。
源可以在Github上找到。
注意:不再维护旧的raven-logback库。强烈建议您迁移到sentry-logback(本文档介绍)。有关更多信息,请查看迁移指南。如果您仍在使用raven-logback,可以在此处找到旧文档。
一、安装
使用Gradle:
implementation 'io.sentry:sentry-logback:5.3.0'
二、配置
以下示例配置在INFO级别记录到标准输出的ConsoleAppender和在WARN级别记录到Sentry服务器的SentryAppender。 ConsoleAppender仅作为非Sentry附加程序的示例提供,该附加程序设置为不同的日志记录阈值,就像您可能已在项目中使用的那样。
使用logback.xml格式的示例配置:
<appender name="Sentry" class="io.sentry.logback.SentryAppender">
<options>
<!-- NOTE: Replace the test DSN below with YOUR OWN DSN to see the events from this app in your Sentry project/dashboard -->
<dsn>
https://examplePublicKey@o0.ingest.sentry.io/0</dsn>
</options>
<!-- Optionally change minimum Event level. Default for Events is ERROR -->
<minimumEventLevel>WARN</minimumEventLevel>
<!-- Optionally change minimum Breadcrumbs level. Default for Breadcrumbs is INFO -->
<minimumBreadcrumbLevel>DEBUG</minimumBreadcrumbLevel>
</appender>
接下来,您需要配置DSN(客户端密钥)以及可选的其他值,例如环境和发布。有关执行此操作的方法,请参阅配置页。https://docs.sentry.io/platforms/java/guides/logback/
三、额外数据
由于Logback提供的MDC系统,可以为事件添加额外的数据。
四、关联TAG
默认情况下,所有MDC参数都存储在Sentry的“附加数据”选项卡下。通过在配置中指定mdctags选项,您可以选择将哪些MDC密钥作为标记发送,这样就可以将它们用作Sentry UI中的过滤器。
- void logWithExtras() {
- // MDC extras
- MDC.put("Environment", "Development");
- MDC.put("OS", "Linux");
- // This sends an event where the Environment and OS MDC values are set as additional data
- logger.error("This is a test");
- }
五、实践
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.slf4j.MDC;
- import org.slf4j.MarkerFactory;
- public class MyClass {
- private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
- private static final Marker MARKER = MarkerFactory.getMarker("myMarker");
- void logSimpleMessage() {
- // This sends a simple event to Sentry
- logger.error("This is a test");
- }
- void logWithBreadcrumbs() {
- // Record a breadcrumb that will be sent with the next event(s),
- // by default the last 100 breadcrumbs are kept.
- Sentry.record(
- new BreadcrumbBuilder().setMessage("User made an action").build()
- );
- // This sends a simple event to Sentry
- logger.error("This is a test");
- }
- void logWithTag() {
- // This sends an event with a tag named 'logback-Marker' to Sentry
- logger.error(MARKER, "This is a test");
- }
- void logWithExtras() {
- // MDC extras
- MDC.put("extra_key", "extra_value");
- // This sends an event with extra data to Sentry
- logger.error("This is a test");
- }
- void logException() {
- try {
- unsafeMethod();
- } catch (Exception e) {
- // This sends an exception event to Sentry
- logger.error("Exception caught", e);
- }
- }
- void unsafeMethod() {
- throw new UnsupportedOperationException("You shouldn't call this!");
- }
- }