完成解决日志sentry日志代码被覆盖的问题

完成切换后台App获取列表和TCP连接后数据响应慢的问题。
This commit is contained in:
2026-03-06 13:52:14 +08:00
parent 3b7445e850
commit c39eb6037d
8 changed files with 183 additions and 43 deletions

View File

@@ -10,17 +10,26 @@ import 'package:intl/intl.dart';
class SentryLoggerImpl implements ILoggerService {
File? _localLogFile;
//调试模式开关
bool _isDebugModeEnabled = false;
@override
Future<void> init() async {
// await SentryFlutter.init((options) {
// options.dsn = EnvConfig.sentryDsn;
// options.environment = EnvConfig.environment;
// // 生产环境只采样 20% 的性能数据,测试环境全开
// options.tracesSampleRate = EnvConfig.isProduction ? 0.2 : 1.0;
// });
await _collectDeviceInfo();
_isDebugModeEnabled = false;
await SentryFlutter.init((options) {
options.dsn = EnvConfig.sentryDsn;
options.environment = EnvConfig.environment;
// 生产环境只采样 20% 的性能数据,测试环境全开
options.tracesSampleRate = EnvConfig.isProduction ? 0.2 : 1.0;
// 动态设置 Sentry 接收的日志级别
// 如果开启调试模式,接收 DEBUG;否则生产环境只接收 INFO 以上
options.debug = _isDebugModeEnabled; // 开启 SDK 内部调试
});
await _collectDeviceInfo();
await _prepareLocalFile();
}
@@ -93,6 +102,54 @@ class SentryLoggerImpl implements ILoggerService {
// 本地写入失败不应崩溃
}
}
@override
void logWithLevel(
String message, {
String level = 'INFO', // 'DEBUG', 'INFO', 'WARNING', 'ERROR'
Map<String, dynamic>? data,
}) {
final timestamp = DateTime.now().toIso8601String();
final logEntry = "[$timestamp] [$level] $message ${data ?? ''}\n";
// --- 策略判断 ---
// 1. 开发环境:全部允许
// 2. 生产环境:
// - 如果是 DEBUG 级别:只有 _isDebugModeEnabled 为 true 时才允许
// - 其他级别:始终允许
bool shouldProcess = !EnvConfig.isProduction ||
level != 'DEBUG' ||
_isDebugModeEnabled;
if (shouldProcess) {
// 写入本地文件
_writeToLocalFile(logEntry);
// 上报 Sentry
SentryLevel sentryLevel;
switch (level) {
case 'DEBUG': sentryLevel = SentryLevel.debug; break;
case 'WARNING': sentryLevel = SentryLevel.warning; break;
case 'ERROR': sentryLevel = SentryLevel.error; break;
default: sentryLevel = SentryLevel.info;
}
// 使用 addBreadcrumb 记录轨迹
Sentry.addBreadcrumb(Breadcrumb(
message: message,
level: sentryLevel,
data: data,
));
// 如果是 ERROR,额外捕获为一个事件
if (level == 'ERROR') {
Sentry.captureMessage(message, level: sentryLevel);
}
}
if (kDebugMode) {
debugPrint(logEntry);
}
}
// 增加一个获取本地日志文件路径的方法,方便你以后做“导出日志”功能
Future<String?> getLocalLogPath() async {