将错误日志发送到 Sentry 方便后期排查和维护
Sentry 简介
Sentry 配置
在 resources
目录下创建 sentry.properties
dsn=你的 dsn
stacktrace.app.packages=
stacktrace.app.packages 必须配置,参考:sentry docs
Logbak 配置
安装依赖
<dependency>
<groupId>io.sentry</groupId>
<artifactId>sentry-logback</artifactId>
<version>${version}</version>
</dependency>
在 resources
目录下创建 logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 引入 spring 的默认配置-->
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<!--非开发环境-->
<springProfile name="!dev">
<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>
<include resource="org/springframework/boot/logging/logback/file-appender.xml"/>
<appender name="Sentry" class="io.sentry.logback.SentryAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
</appender>
<root level="INFO">
<appender-ref ref="FILE"/>
<appender-ref ref="Sentry"/>
</root>
</springProfile>
<!--开发环境-->
<springProfile name="dev">
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</springProfile>
</configuration>
全局处理 Spring 异常
安装依赖
<dependency>
<groupId>io.sentry</groupId>
<artifactId>sentry-spring</artifactId>
<version>${version}</version>
</dependency>
配置 bean
public class SentryExceptionResolverCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return Arrays.stream(context.getEnvironment().getActiveProfiles())
.noneMatch(ProfileConstant.DEV::equals);
}
}
@Bean
@Conditional(SentryExceptionResolverCondition.class)
public HandlerExceptionResolver sentryExceptionResolver() {
return new io.sentry.spring.SentryExceptionResolver();
}
参考
Sentry Docs Java Logback
Sentry Docs Java Spring
写的不好,仅供参考