TF-4136 Add config Sentry
This commit is contained in:
@@ -1,8 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
import 'package:core/utils/build_utils.dart';
|
||||
import 'package:core/utils/platform_info.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:core/utils/sentry/sentry_manager.dart';
|
||||
import 'package:universal_html/html.dart' as html;
|
||||
|
||||
/// ANSI escape colors (Web only)
|
||||
const ansiReset = '\x1B[0m';
|
||||
@@ -73,6 +72,15 @@ void _internalLog(
|
||||
// ignore: avoid_print
|
||||
print('$appLogName $formattedMessage');
|
||||
}
|
||||
|
||||
if (_shouldReportToSentry(level)) {
|
||||
SentryManager.instance.captureException(
|
||||
exception ?? rawMessage,
|
||||
stackTrace: stackTrace,
|
||||
message: rawMessage,
|
||||
extras: extras,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _buildRawMessage(
|
||||
@@ -114,6 +122,10 @@ void _printWebConsole(Level level, String value) {
|
||||
}
|
||||
}
|
||||
|
||||
bool _shouldReportToSentry(Level level) {
|
||||
return level == Level.error || level == Level.critical;
|
||||
}
|
||||
|
||||
void logError(
|
||||
String? message, {
|
||||
Object? exception,
|
||||
@@ -205,18 +217,4 @@ enum Level {
|
||||
info,
|
||||
debug,
|
||||
trace,
|
||||
}
|
||||
|
||||
// Take from: https://flutter.dev/docs/testing/errors
|
||||
void initLogger(VoidCallback runApp) {
|
||||
runZonedGuarded(() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
FlutterError.onError = (details) {
|
||||
FlutterError.dumpErrorToConsole(details);
|
||||
logWarning('AppLogger::initLogger::runZonedGuarded:FlutterError.onError: ${details.stack.toString()}');
|
||||
};
|
||||
runApp.call();
|
||||
}, (error, stack) {
|
||||
logWarning('AppLogger::initLogger::runZonedGuarded:onError: $error | stack: $stack');
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,23 @@
|
||||
|
||||
import 'package:core/utils/app_logger.dart';
|
||||
import 'package:core/utils/platform_info.dart';
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
import 'package:fk_user_agent/fk_user_agent.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
|
||||
class ApplicationManager {
|
||||
static final ApplicationManager _instance = ApplicationManager._internal();
|
||||
|
||||
final DeviceInfoPlugin _deviceInfoPlugin;
|
||||
factory ApplicationManager() => _instance;
|
||||
|
||||
ApplicationManager(this._deviceInfoPlugin);
|
||||
ApplicationManager._internal();
|
||||
|
||||
// Allow overriding in unit tests
|
||||
@visibleForTesting
|
||||
static DeviceInfoPlugin? debugDeviceInfoOverride;
|
||||
|
||||
DeviceInfoPlugin get _deviceInfoPlugin =>
|
||||
debugDeviceInfoOverride ?? DeviceInfoPlugin();
|
||||
|
||||
Future<PackageInfo> getPackageInfo() async {
|
||||
final packageInfo = await PackageInfo.fromPlatform();
|
||||
@@ -18,9 +26,13 @@ class ApplicationManager {
|
||||
}
|
||||
|
||||
Future<String> getVersion() async {
|
||||
final version = (await getPackageInfo()).version;
|
||||
log('ApplicationManager::getVersion: $version');
|
||||
return version;
|
||||
try {
|
||||
final version = (await getPackageInfo()).version;
|
||||
log('ApplicationManager::getVersion: $version');
|
||||
return version;
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> getUserAgent() async {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import 'package:core/utils/app_logger.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
|
||||
class EnvLoader {
|
||||
const EnvLoader._();
|
||||
|
||||
static const String envFileName = 'env.file';
|
||||
static const String appFCMConfigurationPath = "configurations/env.fcm";
|
||||
|
||||
static Future<void> loadEnvFile() async {
|
||||
await loadConfigFromEnv();
|
||||
final mapEnvData = Map<String, String>.from(dotenv.env);
|
||||
await loadFcmConfigFileToEnv(
|
||||
currentMapEnvData: mapEnvData,
|
||||
onCallBack: () async {
|
||||
await loadConfigFromEnv();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
static Future<void> loadFcmConfigFileToEnv({
|
||||
Map<String, String>? currentMapEnvData,
|
||||
VoidCallback? onCallBack,
|
||||
}) async {
|
||||
try {
|
||||
await dotenv.load(
|
||||
fileName: appFCMConfigurationPath,
|
||||
mergeWith: currentMapEnvData ?? {},
|
||||
);
|
||||
} catch (e) {
|
||||
logWarning('EnvLoader::loadFcmConfigFileToEnv: Exception = $e');
|
||||
onCallBack?.call();
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> loadConfigFromEnv() async {
|
||||
try {
|
||||
await dotenv.load(fileName: envFileName);
|
||||
} catch (e) {
|
||||
logWarning('EnvLoader::loadConfigFromEnv:Exception = $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import 'package:core/utils/application_manager.dart';
|
||||
import 'package:core/utils/build_utils.dart';
|
||||
import 'package:core/utils/config/env_loader.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
|
||||
/// Holds configuration values for initializing Sentry.
|
||||
class SentryConfig {
|
||||
// DSN (Data Source Name) endpoint for the Sentry project
|
||||
final String dsn;
|
||||
|
||||
// Running environment (production/staging/dev)
|
||||
final String environment;
|
||||
|
||||
// Current app release version
|
||||
final String release;
|
||||
|
||||
// // Performance monitoring: Set tracesSampleRate to 1.0 to capture 100% of transactions for tracing
|
||||
final double tracesSampleRate;
|
||||
|
||||
// Optional profiling
|
||||
final double profilesSampleRate;
|
||||
|
||||
// Enable logs to be sent to Sentry. To use Sentry.logger.fmt
|
||||
final bool enableLogs;
|
||||
|
||||
// Debug logs during development
|
||||
final bool isDebug;
|
||||
|
||||
// Automatically attaches a screenshot when capturing an error or exception.
|
||||
final bool attachScreenshot;
|
||||
|
||||
// Check if Sentry is available
|
||||
final bool isAvailable;
|
||||
|
||||
SentryConfig({
|
||||
required this.dsn,
|
||||
required this.environment,
|
||||
required this.release,
|
||||
this.tracesSampleRate = 1.0,
|
||||
this.profilesSampleRate = 1.0,
|
||||
this.enableLogs = true,
|
||||
this.isDebug = BuildUtils.isDebugMode,
|
||||
this.attachScreenshot = false,
|
||||
this.isAvailable = false,
|
||||
});
|
||||
|
||||
/// Load configuration from an env file.
|
||||
static Future<SentryConfig> load() async {
|
||||
await EnvLoader.loadConfigFromEnv();
|
||||
|
||||
final sentryAvailable = dotenv.get('SENTRY_ENABLED', fallback: 'false');
|
||||
|
||||
final isAvailable = sentryAvailable == 'true';
|
||||
final sentryDSN = dotenv.get('SENTRY_DSN', fallback: '');
|
||||
final sentryEnvironment = dotenv.get('SENTRY_ENVIRONMENT', fallback: '');
|
||||
|
||||
if (!isAvailable) {
|
||||
throw Exception('Sentry is not available');
|
||||
}
|
||||
|
||||
if (sentryDSN.trim().isEmpty || sentryEnvironment.trim().isEmpty) {
|
||||
throw Exception('Sentry configuration is missing');
|
||||
}
|
||||
|
||||
final appVersion = await ApplicationManager().getVersion();
|
||||
|
||||
return SentryConfig(
|
||||
dsn: sentryDSN,
|
||||
environment: sentryEnvironment,
|
||||
release: appVersion,
|
||||
isAvailable: isAvailable,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:core/utils/sentry/sentry_config.dart';
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
|
||||
class SentryInitializer {
|
||||
static Future<bool> init(FutureOr<void> Function() appRunner) async {
|
||||
final config = await SentryConfig.load();
|
||||
|
||||
await SentryFlutter.init(
|
||||
(options) {
|
||||
options.dsn = config.dsn;
|
||||
options.environment = config.environment;
|
||||
options.release = config.release;
|
||||
options.tracesSampleRate = config.tracesSampleRate;
|
||||
options.profilesSampleRate = config.profilesSampleRate;
|
||||
options.enableLogs = config.enableLogs;
|
||||
options.debug = config.isDebug;
|
||||
options.attachScreenshot = config.attachScreenshot;
|
||||
options.maxRequestBodySize = MaxRequestBodySize.small;
|
||||
|
||||
// Automatically enable breadcrumbs that are appropriate for the current platform
|
||||
options.enableBreadcrumbTrackingForCurrentPlatform();
|
||||
|
||||
// Assign the callback to process events before sending them to Sentry
|
||||
options.beforeSend = _beforeSendHandler;
|
||||
},
|
||||
appRunner: appRunner,
|
||||
);
|
||||
|
||||
return config.isAvailable;
|
||||
}
|
||||
|
||||
/// Handler executed before sending an event to Sentry
|
||||
static Future<SentryEvent?> _beforeSendHandler(
|
||||
SentryEvent event,
|
||||
Hint? hint,
|
||||
) async {
|
||||
// Ignore AssertionError events
|
||||
if (event.throwable is AssertionError) {
|
||||
return null;
|
||||
}
|
||||
return event;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:core/utils/app_logger.dart';
|
||||
import 'package:core/utils/sentry/sentry_initializer.dart';
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
|
||||
/// Controls Sentry initialization and error reporting.
|
||||
class SentryManager {
|
||||
SentryManager._();
|
||||
|
||||
static final SentryManager instance = SentryManager._();
|
||||
|
||||
bool _isSentryAvailable = false;
|
||||
|
||||
bool get isSentryAvailable => _isSentryAvailable;
|
||||
|
||||
/// Initialize Sentry. App still runs if init fails.
|
||||
Future<void> initialize({
|
||||
required FutureOr<void> Function() appRunner,
|
||||
required FutureOr<void> Function() fallBackRunner,
|
||||
}) async {
|
||||
try {
|
||||
_isSentryAvailable = await SentryInitializer.init(appRunner);
|
||||
log('[SentryManager] Sentry initialized: $_isSentryAvailable');
|
||||
} catch (e, st) {
|
||||
logError('[SentryManager] Init failed', exception: e, stackTrace: st);
|
||||
await fallBackRunner();
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture an exception. Metadata is attached as breadcrumbs.
|
||||
Future<void> captureException(
|
||||
dynamic exception, {
|
||||
StackTrace? stackTrace,
|
||||
String? message,
|
||||
Map<String, dynamic>? extras,
|
||||
}) async {
|
||||
if (!_isSentryAvailable) return;
|
||||
|
||||
await Sentry.captureException(
|
||||
exception,
|
||||
stackTrace: stackTrace,
|
||||
withScope: (scope) {
|
||||
scope.addBreadcrumb(
|
||||
Breadcrumb(
|
||||
message: message ?? exception.toString(),
|
||||
data: extras,
|
||||
level: SentryLevel.error,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Capture a text message. Metadata also goes into breadcrumbs.
|
||||
Future<void> captureMessage(
|
||||
String message, {
|
||||
SentryLevel level = SentryLevel.info,
|
||||
Map<String, dynamic>? extras,
|
||||
}) async {
|
||||
if (!_isSentryAvailable) return;
|
||||
|
||||
await Sentry.captureMessage(
|
||||
message,
|
||||
level: level,
|
||||
withScope: (scope) {
|
||||
scope.addBreadcrumb(
|
||||
Breadcrumb(
|
||||
message: message,
|
||||
data: extras,
|
||||
level: SentryLevel.info,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> setUser(SentryUser user) async {
|
||||
if (!_isSentryAvailable) return;
|
||||
|
||||
try {
|
||||
await Sentry.configureScope((scope) => scope.setUser(user));
|
||||
log('[SentryManager] User set: ${user.email}');
|
||||
} catch (e, st) {
|
||||
logError('[SentryManager] Set user failed', exception: e, stackTrace: st);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> clearUser() async {
|
||||
if (!_isSentryAvailable) return;
|
||||
|
||||
try {
|
||||
await Sentry.configureScope((scope) => scope.setUser(null));
|
||||
log('[SentryManager] User cleared');
|
||||
} catch (e, st) {
|
||||
logError(
|
||||
'[SentryManager] Clear user failed',
|
||||
exception: e,
|
||||
stackTrace: st,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user