sentry库提供了一个java.util.logging Handler,它将记录的异常发送给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存储库。
二、事例
以下示例配置在INFO级别记录到标准输出的ConsoleHandler和在WARN级别记录到Sentry服务器的SentryHandler。 ConsoleHandler仅作为设置为不同日志记录阈值的非Sentry appender的示例提供,就像您可能已在项目中使用的那样。
使用logging.properties格式的示例配置:
# Enable the Console and Sentry handlers
handlers=java.util.logging.ConsoleHandler,io.sentry.jul.SentryHandler
# Set the default log level to INFO
.level=INFO
# Override the Sentry handler log level to WARNING
io.sentry.jul.SentryHandler.level=WARNING
启动应用程序时,将java.util.logging.config.file添加到系统属性,并将logging.properties的完整路径作为其值:
$ java -Djava.util.logging.config.file=/path/to/app.properties MyClass
接下来,您需要配置DSN(客户端密钥)以及可选的其他值,例如环境和发布。有关执行此操作的方法,请参阅配置页。
三、实践
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyClass {
private static final Logger logger = Logger.getLogger(MyClass.class.getName());
void logSimpleMessage() {
// This sends a simple event to Sentry
logger.error(Level.INFO, "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 logException() {
try {
unsafeMethod();
} catch (Exception e) {
// This sends an exception event to Sentry
logger.error(Level.SEVERE, "Exception caught", e);
}
}
void unsafeMethod() {
throw new UnsupportedOperationException("You shouldn't call this!");
}
}