diff --git a/lib/application/account/account_notifier.dart b/lib/application/account/account_notifier.dart index 5e3f25973..c9af74ec0 100644 --- a/lib/application/account/account_notifier.dart +++ b/lib/application/account/account_notifier.dart @@ -2,6 +2,7 @@ part of 'providers.dart'; class _AccountNotifier extends AutoDisposeFamilyAsyncNotifier { + final _logger = Logger('AccountNotifier'); @override FutureOr build(String name) async { final repository = ref.read(AccountProviders.accountsRepository); @@ -22,7 +23,7 @@ class _AccountNotifier state = AsyncValue.data(account.copyWith()); } catch (e, stack) { - log('Refresh failed', error: e, stackTrace: stack); + _logger.severe('Refresh failed', e, stack); } } @@ -38,13 +39,17 @@ class _AccountNotifier Future refreshRecentTransactions() => _refresh( (account) async { - log('${DateTime.now()} Start method refreshRecentTransactions for ${account.nameDisplayed}'); + _logger.fine( + 'Start method refreshRecentTransactions for ${account.nameDisplayed}', + ); await Future.wait([ _refreshRecentTransactions(account), _refreshBalance(account), account.updateFungiblesTokens(), ]); - log('${DateTime.now()} End method refreshRecentTransactions for ${account.nameDisplayed}'); + _logger.fine( + 'End method refreshRecentTransactions for ${account.nameDisplayed}', + ); }, ); @@ -77,7 +82,7 @@ class _AccountNotifier Future refreshAll() => _refresh( (account) async { - log('${DateTime.now()} Start method refreshAll'); + _logger.fine('Start method refreshAll'); final session = ref.read(SessionProviders.session).loggedIn!; final tokenInformation = await ref.read( NFTProviders.getNFTList( @@ -96,7 +101,7 @@ class _AccountNotifier tokenInformation.$2, ), ]); - log('${DateTime.now()} End method refreshAll'); + _logger.fine('End method refreshAll'); }, ); } diff --git a/lib/application/account/providers.dart b/lib/application/account/providers.dart index 62c42d866..ed279991d 100644 --- a/lib/application/account/providers.dart +++ b/lib/application/account/providers.dart @@ -1,7 +1,6 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:async'; -import 'dart:developer'; import 'package:aewallet/application/connectivity_status.dart'; import 'package:aewallet/application/nft/nft.dart'; @@ -12,6 +11,7 @@ import 'package:aewallet/model/data/account.dart'; import 'package:aewallet/model/data/account_token.dart'; import 'package:collection/collection.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'account_notifier.dart'; diff --git a/lib/application/authentication/authentication.dart b/lib/application/authentication/authentication.dart index de3d33646..d513977ca 100644 --- a/lib/application/authentication/authentication.dart +++ b/lib/application/authentication/authentication.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:developer'; import 'package:aewallet/domain/models/authentication.dart'; import 'package:aewallet/domain/repositories/authentication.dart'; @@ -13,6 +12,7 @@ import 'package:aewallet/model/privacy_mask_option.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'authentication.freezed.dart'; @@ -70,7 +70,7 @@ abstract class AuthenticationProviders { static final authenticationGuard = AsyncNotifierProvider< AuthenticationGuardNotifier, AuthenticationGuardState>( AuthenticationGuardNotifier.new, - name: AuthenticationGuardNotifier.logName, + name: AuthenticationGuardNotifier._logger.name, ); static final passwordAuthentication = StateNotifierProvider< diff --git a/lib/application/authentication/auto_lock_guard.dart b/lib/application/authentication/auto_lock_guard.dart index a033c9f51..f593aab9b 100644 --- a/lib/application/authentication/auto_lock_guard.dart +++ b/lib/application/authentication/auto_lock_guard.dart @@ -12,7 +12,8 @@ typedef LastInteractionDateValue = ({ class LastInteractionDateNotifier extends AsyncNotifier { - static const _logName = 'AuthenticationGuard-LastInteractionDateProvider'; + static final _logger = + Logger('AuthenticationGuard-LastInteractionDateProvider'); @override FutureOr build() async { @@ -40,7 +41,7 @@ class LastInteractionDateNotifier await ref .read(AuthenticationProviders.authenticationRepository) .setLastInteractionDate(date); - log('persist $date', name: _logName); + _logger.info('persist $date'); state = AsyncValue.data( ( date: date, @@ -50,7 +51,7 @@ class LastInteractionDateNotifier } Future clear() async { - log('clear storage', name: _logName); + _logger.fine('clear storage'); await ref .read(AuthenticationProviders.authenticationRepository) @@ -68,7 +69,7 @@ class LastInteractionDateNotifier final _lastInteractionDateNotifierProvider = AsyncNotifierProvider< LastInteractionDateNotifier, LastInteractionDateValue>( LastInteractionDateNotifier.new, - name: LastInteractionDateNotifier._logName, + name: LastInteractionDateNotifier._logger.name, ); final _vaultLockedProvider = Provider( @@ -104,7 +105,7 @@ class AuthenticationGuardState with _$AuthenticationGuardState { @Riverpod(keepAlive: true) class AuthenticationGuardNotifier extends AsyncNotifier { - static const logName = 'AuthenticationGuard-Provider'; + static final _logger = Logger('AuthenticationGuard-Provider'); @override Future build() async { @@ -178,9 +179,8 @@ class AuthenticationGuardNotifier } Future scheduleNextStartupAutolock() async { - log( + _logger.info( 'Schedule next startup Autolock', - name: logName, ); final loadedState = state.valueOrNull; @@ -193,9 +193,8 @@ class AuthenticationGuardNotifier } void scheduleAutolock() { - log( + _logger.info( 'Schedule Autolock', - name: logName, ); final loadedState = state.valueOrNull; @@ -207,9 +206,8 @@ class AuthenticationGuardNotifier } Future unscheduleAutolock() async { - log( + _logger.info( 'Unschedule Autolock', - name: logName, ); await ref.read(_lastInteractionDateNotifierProvider.notifier).clear(); } diff --git a/lib/application/check_transaction_worker/provider.dart b/lib/application/check_transaction_worker/provider.dart index e74689af5..a14c6d7c9 100644 --- a/lib/application/check_transaction_worker/provider.dart +++ b/lib/application/check_transaction_worker/provider.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:developer'; import 'package:aewallet/application/account/providers.dart'; import 'package:aewallet/application/connectivity_status.dart'; @@ -9,6 +8,7 @@ import 'package:aewallet/service/app_service.dart'; import 'package:aewallet/util/get_it_instance.dart'; import 'package:archethic_lib_dart/archethic_lib_dart.dart'; import 'package:flutter/material.dart'; +import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'provider.g.dart'; @@ -22,23 +22,23 @@ abstract class CheckTransactionsProvider { class _CheckTransactionNotifier extends AsyncNotifier> { Timer? _checkTransactionsTimer; + static final _logger = Logger('CheckTransactionScheduler'); Future _cancelCheck() async { if (_checkTransactionsTimer == null) return; - log('cancelling scheduler', name: 'CheckTransactionScheduler'); + _logger.info('cancelling scheduler'); _checkTransactionsTimer?.cancel(); _checkTransactionsTimer = null; } Future _scheduleCheck() async { if (_checkTransactionsTimer != null && _checkTransactionsTimer!.isActive) { - log( + _logger.info( 'start abort : scheduler already running', - name: 'CheckTransactionScheduler', ); return; } - log('starting scheduler', name: 'CheckTransactionScheduler'); + _logger.info('starting scheduler'); _checkTransactionsTimer = Timer.periodic( const Duration(seconds: 30), @@ -137,11 +137,10 @@ class _CheckTransactionNotifier state = AsyncValue.data(transactionsToNotify); } catch (e, stack) { - log( + _logger.severe( 'refresh failed.', - name: 'CheckTransactionScheduler', - error: e, - stackTrace: stack, + e, + stack, ); } }, diff --git a/lib/application/migrations/437.dart b/lib/application/migrations/437.dart index 52386ed35..11b590d90 100644 --- a/lib/application/migrations/437.dart +++ b/lib/application/migrations/437.dart @@ -5,12 +5,12 @@ part of 'migration_manager.dart'; final migration_437 = LocalDataMigration( minAppVersion: 437, run: (ref) async { + final logger = Logger('DataMigration - 437'); // We need to reload keychain because of account's name structure change // https://github.com/archethic-foundation/archethic-wallet/pull/759 if (ref.read(SessionProviders.session).isLoggedOut) { - log( + logger.info( 'Skipping migration 437 process : user logged out.', - name: logName, ); return; } diff --git a/lib/application/migrations/526.dart b/lib/application/migrations/526.dart index 4de03bb2c..8c5831a5b 100644 --- a/lib/application/migrations/526.dart +++ b/lib/application/migrations/526.dart @@ -7,7 +7,7 @@ part of 'migration_manager.dart'; final migration_526 = LocalDataMigration( minAppVersion: 526, run: (ref) async { - const logName = 'DataMigration_EncryptedPassword'; + final logger = Logger('DataMigration_EncryptedPassword'); const _kSourceBox = '_vaultBox'; const _kDestinationBox = 'NonWebAuthentication'; @@ -20,13 +20,13 @@ final migration_526 = LocalDataMigration( Future _migratePassword(Box sourceBox, Box destinationBox) async { final encryptedPassword = sourceBox.get(_kPassword); if (encryptedPassword == null) { - log('No password to migrate', name: logName); + logger.info('No password to migrate'); return; } final seed = sourceBox.get(_kSeed); if (seed == null) { - log('No password to migrate', name: logName); + logger.info('No password to migrate'); return; } @@ -38,9 +38,9 @@ final migration_526 = LocalDataMigration( await destinationBox.put(_kPassword, rawPassword); await sourceBox.delete(_kPassword); - log('Password migrated', name: logName); + logger.info('Password migrated'); } catch (e) { - log('Password decryption failed', name: logName); + logger.severe('Password decryption failed'); return; } } @@ -52,13 +52,13 @@ final migration_526 = LocalDataMigration( ) async { final data = sourceBox.get(key); if (data == null) { - log('No $key to migrate', name: logName); + logger.info('No $key to migrate'); return; } await destinationBox.put(key, data); await sourceBox.delete(key); - log('$key migrated', name: logName); + logger.info('$key migrated'); } Future _prepareCipher() async { @@ -81,7 +81,7 @@ final migration_526 = LocalDataMigration( encryptionCipher: cipher, ); } catch (e) { - log('Unable to open box', name: logName); + logger.severe('Unable to open box'); return null; } } @@ -94,7 +94,7 @@ final migration_526 = LocalDataMigration( } if (sourceBox == null) { - log('No authentication data to migrate', name: logName); + logger.info('No authentication data to migrate'); return; } diff --git a/lib/application/migrations/migration_manager.dart b/lib/application/migrations/migration_manager.dart index 109f58607..a98c56499 100644 --- a/lib/application/migrations/migration_manager.dart +++ b/lib/application/migrations/migration_manager.dart @@ -1,5 +1,3 @@ -import 'dart:developer'; - import 'package:aewallet/application/account/providers.dart'; import 'package:aewallet/application/contact.dart'; import 'package:aewallet/application/session/session.dart'; @@ -12,6 +10,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:hive/hive.dart'; +import 'package:logging/logging.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; @@ -21,8 +20,6 @@ part '526.dart'; part 'migration_manager.freezed.dart'; part 'migration_manager.g.dart'; -const logName = 'DataMigration'; - @freezed class LocalDataMigrationState with _$LocalDataMigrationState { const factory LocalDataMigrationState({ @@ -42,6 +39,8 @@ class LocalDataMigrationNotifier extends AutoDisposeNotifier { LocalDataMigrationNotifier(); + static final _logger = Logger('DataMigration'); + @override LocalDataMigrationState build() { return const LocalDataMigrationState(); @@ -56,12 +55,12 @@ class LocalDataMigrationNotifier final currentDataVersion = await preferences.getCurrentDataVersion(); if (currentDataVersion == null) { - log('Application freshly installed. No migration to run', name: logName); + _logger.info('Application freshly installed. No migration to run'); await _updateCurrentDataVersion(); return; } - log('Current data version: $currentDataVersion', name: logName); + _logger.info('Current data version: $currentDataVersion'); final migrations = ref.read(_migrationsProvider) ..sort( @@ -70,16 +69,14 @@ class LocalDataMigrationNotifier for (final migration in migrations) { if (migration.shouldSkip(currentDataVersion)) { - log( + _logger.info( 'Skipping migration from version ${migration.minAppVersion}', - name: logName, ); continue; } - log( + _logger.info( 'Running migration from version ${migration.minAppVersion}', - name: logName, ); _setMigrationInProgress(true); @@ -89,7 +86,7 @@ class LocalDataMigrationNotifier _setMigrationInProgress(false); } - log('Migrations successfully executed', name: logName); + _logger.info('Migrations successfully executed'); await _updateCurrentDataVersion(); } @@ -100,16 +97,14 @@ class LocalDataMigrationNotifier await CurrentVersionRepository().getCurrentAppVersion(); final currentAppBuildNumber = int.tryParse(currentAppVersion.$2); if (currentAppBuildNumber == null) { - log( + _logger.info( 'Failed to update current data version : Unable to determine application build number ($currentAppVersion).', - name: logName, ); return; } await preferences.setCurrentDataVersion(currentAppBuildNumber); - log( + _logger.info( 'Current data version updated to $currentAppBuildNumber.', - name: logName, ); } } diff --git a/lib/application/nft/nft.dart b/lib/application/nft/nft.dart index af4ae653d..23259bb53 100644 --- a/lib/application/nft/nft.dart +++ b/lib/application/nft/nft.dart @@ -1,5 +1,4 @@ import 'dart:convert'; -import 'dart:developer' as dev; import 'dart:typed_data'; import 'package:aewallet/model/blockchain/keychain_secured_infos.dart'; @@ -9,6 +8,7 @@ import 'package:aewallet/model/keychain_service_keypair.dart'; import 'package:aewallet/service/app_service.dart'; import 'package:aewallet/util/get_it_instance.dart'; import 'package:archethic_lib_dart/archethic_lib_dart.dart'; +import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'nft.g.dart'; @@ -52,6 +52,8 @@ Future<(List, List)> _getNFTList( } class NFTRepository { + static final _logger = Logger('NFTRepository'); + Future isAccountOwner( String accountAddress, String tokenAddress, @@ -257,8 +259,8 @@ class NFTRepository { final decryptedSecret = aesDecrypt(ownership.secret, aesKey); try { propertiesDecrypted.addAll(json.decode(utf8.decode(decryptedSecret))); - } catch (e) { - dev.log('Decryption error $e'); + } catch (e, stack) { + _logger.severe('Decryption error', e, stack); } } } diff --git a/lib/application/oracle/provider.dart b/lib/application/oracle/provider.dart index 26d3f6c8d..ef134154b 100644 --- a/lib/application/oracle/provider.dart +++ b/lib/application/oracle/provider.dart @@ -1,11 +1,11 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:async'; -import 'dart:developer'; import 'package:aewallet/application/oracle/state.dart'; import 'package:aewallet/util/get_it_instance.dart'; import 'package:archethic_lib_dart/archethic_lib_dart.dart'; +import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'provider.g.dart'; @@ -14,10 +14,12 @@ part 'provider.g.dart'; class _ArchethicOracleUCONotifier extends Notifier { ArchethicOracle? archethicOracle; + static final _logger = Logger('ArchethicOracleUCONotifier'); + @override ArchethicOracleUCO build() { ref.onDispose(() { - log('dispose ArchethicOracleUCONotifier'); + _logger.info('dispose ArchethicOracleUCONotifier'); if (archethicOracle != null) { sl .get() @@ -46,7 +48,7 @@ class _ArchethicOracleUCONotifier extends Notifier { } void _fillInfo(OracleUcoPrice oracleUcoPrice) { - log('Oracle: ${oracleUcoPrice.timestamp}, ${oracleUcoPrice.uco}'); + _logger.info('Oracle: ${oracleUcoPrice.timestamp}, ${oracleUcoPrice.uco}'); state = state.copyWith( timestamp: oracleUcoPrice.timestamp ?? 0, eur: oracleUcoPrice.uco!.eur ?? 0, diff --git a/lib/application/utils.dart b/lib/application/utils.dart index dabbb2699..d3035c4a0 100644 --- a/lib/application/utils.dart +++ b/lib/application/utils.dart @@ -1,15 +1,16 @@ import 'dart:async'; -import 'dart:developer'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:logging/logging.dart'; extension WidgetRefExt on WidgetRef { Future waitUntil( ProviderListenable provider, bool Function(T? previous, T next) predicate, ) async { + final _logger = Logger('WaitUntilProvider ${provider.runtimeType}'); if (predicate(null, read(provider))) return; - log('start', name: 'WaitUntilProvider ${provider.runtimeType}'); + _logger.info('start'); final waitCompleter = Completer(); ProviderSubscription? subscription; @@ -20,15 +21,16 @@ extension WidgetRefExt on WidgetRef { subscription?.close(); waitCompleter.complete(); - log( + _logger.info( 'predicate verified', - name: 'WaitUntilProvider ${provider.runtimeType}', ); }, onError: (error, stackTrace) { subscription?.close(); waitCompleter.completeError(error, stackTrace); - log('canceled', name: 'WaitUntilProvider ${provider.runtimeType}'); + _logger.info( + 'canceled', + ); }, ); diff --git a/lib/application/verified_tokens.dart b/lib/application/verified_tokens.dart index 5b6517f85..ababb58b2 100644 --- a/lib/application/verified_tokens.dart +++ b/lib/application/verified_tokens.dart @@ -1,5 +1,4 @@ import 'dart:convert'; -import 'dart:developer'; import 'package:aewallet/application/settings/settings.dart'; import 'package:aewallet/domain/models/verified_tokens.dart'; @@ -7,6 +6,7 @@ import 'package:aewallet/infrastructure/repositories/verified_tokens_list.dart'; import 'package:aewallet/model/available_networks.dart'; import 'package:aewallet/util/get_it_instance.dart'; import 'package:archethic_lib_dart/archethic_lib_dart.dart'; +import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'verified_tokens.g.dart'; @@ -15,6 +15,8 @@ part 'verified_tokens.g.dart'; class _VerifiedTokensNotifier extends Notifier> { List? verifiedTokensList; + static final _logger = Logger('VerifiedTokensNotifier'); + @override List build() { return const []; @@ -31,7 +33,8 @@ class _VerifiedTokensNotifier extends Notifier> { final verifiedTokensFromNetwork = await ref .watch(_verifiedTokensRepositoryProvider) .getVerifiedTokensFromNetwork(networkSettings.network); - log('Verified tokens list (${networkSettings.network}) $verifiedTokensFromNetwork'); + _logger.info( + 'Verified tokens list (${networkSettings.network}) $verifiedTokensFromNetwork'); state = verifiedTokensFromNetwork; } } @@ -75,6 +78,8 @@ Future _isVerifiedToken( } class VerifiedTokensRepository { + static final _logger = Logger('VerifiedTokensRepository'); + Future getVerifiedTokens() async { return VerifiedTokensList().getVerifiedTokens(); } @@ -111,7 +116,7 @@ class VerifiedTokensRepository { jsonDecode(lastAddressMap[txAddress]!.data!.content!); if (jsonMap['verifiedTokens'] != null && jsonMap['verifiedTokens']['tokens'] != null) { - log('Verified tokens ${jsonMap['verifiedTokens']['tokens']}'); + _logger.info('Verified tokens ${jsonMap['verifiedTokens']['tokens']}'); return List.from(jsonMap['verifiedTokens']['tokens']); } } diff --git a/lib/domain/usecases/read_usecases.dart b/lib/domain/usecases/read_usecases.dart index 56ce5db5a..569ad5764 100644 --- a/lib/domain/usecases/read_usecases.dart +++ b/lib/domain/usecases/read_usecases.dart @@ -1,12 +1,11 @@ -import 'dart:developer'; - import 'package:aewallet/domain/models/core/failures.dart'; import 'package:aewallet/domain/models/core/result.dart'; import 'package:aewallet/domain/usecases/usecase.dart'; +import 'package:logging/logging.dart'; /// Handles read strategies and persistent cache. mixin ReadStrategy { - final String _logName = 'Read $ValueT Usecase'; + final _logger = Logger('Read $ValueT Usecase'); /// Reads data from local data source. Future getLocal(CommandT command); @@ -18,32 +17,38 @@ mixin ReadStrategy { Future getRemote(CommandT command); Future> _getFromRemoteFirst(CommandT command) async { - log('Get from remote first', name: _logName); + _logger.info('Get from remote first'); try { final remoteValue = await getRemote(command); if (remoteValue != null) { - log('Using and saving remote value', name: _logName); + _logger.info('Using and saving remote value'); await saveLocal(command, remoteValue); return Result.success(remoteValue); } } catch (e, stackTrace) { - log('Remote read failed', - name: _logName, error: e, stackTrace: stackTrace,); + _logger.severe( + 'Remote read failed', + e, + stackTrace, + ); } try { final localValue = await getLocal(command); if (localValue != null) { - log('Using local value', name: _logName); + _logger.info('Using local value'); return Result.success(localValue); } } catch (e, stackTrace) { - log('Local read failed', - name: _logName, error: e, stackTrace: stackTrace,); + _logger.severe( + 'Local read failed', + e, + stackTrace, + ); } - log('Unable to fetch local or remote value', name: _logName); + _logger.info('Unable to fetch local or remote value'); return const Result.failure( Failure.other( cause: 'Unable to fetch local or remote value', @@ -52,32 +57,38 @@ mixin ReadStrategy { } Future> _getFromLocalFirst(CommandT command) async { - log('Get from local first', name: _logName); + _logger.info('Get from local first'); try { final localValue = await getLocal(command); if (localValue != null) { - log('Using local value', name: _logName); + _logger.info('Using local value'); return Result.success(localValue); } } catch (e, stackTrace) { - log('Local read failed', - name: _logName, error: e, stackTrace: stackTrace,); + _logger.severe( + 'Local read failed', + e, + stackTrace, + ); } try { final remoteValue = await getRemote(command); if (remoteValue != null) { - log('Using and saving remote value', name: _logName); + _logger.info('Using and saving remote value'); await saveLocal(command, remoteValue); return Result.success(remoteValue); } } catch (e, stackTrace) { - log('Remote read failed', - name: _logName, error: e, stackTrace: stackTrace,); + _logger.severe( + 'Remote read failed', + e, + stackTrace, + ); } - log('Unable to fetch local or remote value', name: _logName); + _logger.info('Unable to fetch local or remote value'); return const Result.failure( Failure.other( diff --git a/lib/domain/usecases/transaction/send_transaction.dart b/lib/domain/usecases/transaction/send_transaction.dart index eb878b666..961930ad0 100644 --- a/lib/domain/usecases/transaction/send_transaction.dart +++ b/lib/domain/usecases/transaction/send_transaction.dart @@ -1,7 +1,6 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:async'; -import 'dart:developer'; import 'package:aewallet/domain/models/app_wallet.dart'; import 'package:aewallet/domain/models/core/result.dart'; @@ -11,6 +10,7 @@ import 'package:aewallet/model/data/account.dart'; import 'package:aewallet/util/keychain_util.dart'; import 'package:archethic_lib_dart/archethic_lib_dart.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:logging/logging.dart'; part 'send_transaction.freezed.dart'; @@ -32,6 +32,7 @@ class SendTransactionCommand with _$SendTransactionCommand { } extension SendTransactionCommandConversion on SendTransactionCommand { + static final _logger = Logger('SendTransactionCommand'); Future toArchethicTransaction({ required AppWallet wallet, required Account senderAccount, @@ -92,7 +93,7 @@ extension SendTransactionCommandConversion on SendTransactionCommand { return signedTransaction; } catch (e, stack) { - log('Transaction creation failed', error: e, stackTrace: stack); + _logger.severe('Transaction creation failed', e, stack); return null; } } @@ -117,7 +118,7 @@ class SendTransactionUseCase SendTransactionCommand command, { UseCaseProgressListener? onProgress, }) async { - const logName = 'SendTransactionUseCase'; + final _logger = Logger('SendTransactionUseCase'); final operationCompleter = Completer>(); @@ -157,17 +158,17 @@ class SendTransactionUseCase ), ); if (confirmation.isFullyConfirmed) { - log('Final confirmation received : $confirmation', name: logName); + _logger.info('Final confirmation received : $confirmation'); operationCompleter.complete( Result.success(confirmation), ); return; } - log('Confirmation received : $confirmation', name: logName); + _logger.info('Confirmation received : $confirmation'); }, onError: (error) async { - log('Transaction error received', name: logName, error: error); + _logger.severe('Transaction error received', error); _fail(error); }, ); diff --git a/lib/infrastructure/datasources/authent_nonweb.secured_hive.dart b/lib/infrastructure/datasources/authent_nonweb.secured_hive.dart index 0eea35f54..b21d77df7 100644 --- a/lib/infrastructure/datasources/authent_nonweb.secured_hive.dart +++ b/lib/infrastructure/datasources/authent_nonweb.secured_hive.dart @@ -1,11 +1,10 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later -import 'dart:developer'; - import 'package:aewallet/infrastructure/datasources/hive.extension.dart'; import 'package:aewallet/infrastructure/datasources/vault/vault.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:hive/hive.dart'; +import 'package:logging/logging.dart'; /// Class used on non-web platforms only /// It stores authent infos in FlutterSecureStorage @@ -14,6 +13,8 @@ import 'package:hive/hive.dart'; class AuthentHiveSecuredDatasource { AuthentHiveSecuredDatasource._(this._box); + static final _logger = Logger('AuthentHiveSecuredDatasource'); + static const String _authenticationBox = 'NonWebAuthentication'; final Box _box; @@ -76,11 +77,7 @@ class AuthentHiveSecuredDatasource { encryptionCipher: await _prepareCipher(), ); } catch (e, stack) { - log( - 'Failed to open Hive encrypted Box<$E>($name).', - error: e, - stackTrace: stack, - ); + _logger.severe('Failed to open Hive encrypted Box<$E>($name).', e, stack); rethrow; } } diff --git a/lib/infrastructure/datasources/contacts.hive.dart b/lib/infrastructure/datasources/contacts.hive.dart index e1758312e..12af9369e 100644 --- a/lib/infrastructure/datasources/contacts.hive.dart +++ b/lib/infrastructure/datasources/contacts.hive.dart @@ -1,11 +1,10 @@ -import 'dart:developer'; - import 'package:aewallet/infrastructure/datasources/hive.extension.dart'; import 'package:aewallet/model/data/contact.dart'; import 'package:aewallet/ui/util/contact_formatters.dart'; import 'package:aewallet/util/get_it_instance.dart'; import 'package:archethic_lib_dart/archethic_lib_dart.dart'; import 'package:hive/hive.dart'; +import 'package:logging/logging.dart'; class ContactsHiveDatasource { ContactsHiveDatasource._(); @@ -14,6 +13,7 @@ class ContactsHiveDatasource { return _instance ?? (_instance = ContactsHiveDatasource._()); } + static final _logger = Logger('ContactsHiveDatasource'); static ContactsHiveDatasource? _instance; static const String contactsTable = 'contacts'; @@ -92,7 +92,7 @@ class ContactsHiveDatasource { Contact? contactSelected; final address = hash(publicKey); - log('address contact: ${uint8ListToHex(address)}'); + _logger.info('address contact: ${uint8ListToHex(address)}'); contactSelected = await getContactWithAddress(uint8ListToHex(address)); if (contactSelected == null) { diff --git a/lib/infrastructure/datasources/notification.remote.dart b/lib/infrastructure/datasources/notification.remote.dart index 80378c617..6f73b5ac2 100644 --- a/lib/infrastructure/datasources/notification.remote.dart +++ b/lib/infrastructure/datasources/notification.remote.dart @@ -1,11 +1,11 @@ import 'dart:async'; import 'dart:convert'; -import 'dart:developer'; import 'dart:io'; import 'dart:ui'; import 'package:aewallet/domain/repositories/notifications_repository.dart'; import 'package:http/http.dart' as http; +import 'package:logging/logging.dart'; import 'package:socket_io_client/socket_io_client.dart' as socket_io; import 'package:socket_io_client/socket_io_client.dart'; @@ -19,23 +19,23 @@ class NotificationBackendClient { OptionBuilder().setTransports(['websocket']).build(), ) ..onConnectError((e) { - log('Connection failed', name: _logName, error: e); + _logger.severe('Connection failed', e); }) ..onConnect((_) { - log('Did connect', name: _logName); + _logger.info('Did connect'); onConnect(); }) ..onReconnect((_) { - log('Did reconnect', name: _logName); + _logger.info('Did reconnect'); }) ..onDisconnect((_) { - log('Did disconnect', name: _logName); + _logger.info('Did disconnect'); }); } final VoidCallback onConnect; - static const _logName = 'NotificationBackendClient'; + static final _logger = Logger('NotificationBackendClient'); final String notificationBackendUrl; @@ -48,7 +48,7 @@ class NotificationBackendClient { socket.on( 'TxSent', (event) { - log('TxSent event received', name: _logName); + _logger.info('TxSent event received'); _eventsStreamController.add(TxSentEvent.fromJson(event)); }, ); diff --git a/lib/infrastructure/datasources/vault/vault.dart b/lib/infrastructure/datasources/vault/vault.dart index d5b9c2bf3..8109dd5f1 100644 --- a/lib/infrastructure/datasources/vault/vault.dart +++ b/lib/infrastructure/datasources/vault/vault.dart @@ -1,5 +1,4 @@ import 'dart:convert'; -import 'dart:developer'; import 'package:aewallet/domain/models/core/failures.dart'; import 'package:aewallet/infrastructure/datasources/hive.extension.dart'; @@ -7,6 +6,7 @@ import 'package:archethic_lib_dart/archethic_lib_dart.dart' as archethic; import 'package:flutter/foundation.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:hive_flutter/hive_flutter.dart'; +import 'package:logging/logging.dart'; import 'package:pointycastle/export.dart'; part 'lib/password_vault_cipher.dart'; @@ -78,7 +78,7 @@ class Vault { late final VaultCipherFactory _cipherFactory; - static const _logName = 'Vault'; + static final _logger = Logger('Vault'); static Vault? _instance; @@ -94,9 +94,8 @@ class Vault { } Future lock() async { - log( + _logger.info( 'Locking vault', - name: _logName, ); await Hive.close(); _vaultCipher = null; @@ -104,18 +103,16 @@ class Vault { } Future unlock(String password) async { - log( + _logger.info( 'Unlocking vault', - name: _logName, ); _vaultCipher = _cipherFactory.build(password); // Ensures we are able to retrieve the encryption key await _vaultCipher!.get(); isLocked.value = false; - log( + _logger.info( 'Vault unlocked', - name: _logName, ); } @@ -128,21 +125,18 @@ class Vault { } Future clear(String name) async { - log( + _logger.info( 'Deleting vault box $name...', - name: _logName, ); await Hive.deleteBox(name); - log( + _logger.info( '... vault box $name deleted', - name: _logName, ); } Future clearSecureKey() async { - log( + _logger.info( 'Clearing vault secure key', - name: _logName, ); await _cipherFactory.clear(); await lock(); @@ -151,9 +145,8 @@ class Vault { Future updateSecureKey( String passphrase, ) async { - log( + _logger.info( 'Updating vault secure key', - name: _logName, ); if (_vaultCipher == null) { throw const Failure.locked(); @@ -164,9 +157,8 @@ class Vault { Future> openBox( String name, ) async { - log( + _logger.info( 'Opening box $name', - name: _logName, ); await applyAutolock(); if (Hive.isBoxOpen(name)) { @@ -181,11 +173,10 @@ class Vault { encryptionCipher: await encryptionCipher, ); } catch (e, stack) { - log( + _logger.severe( 'Failed to open Hive encrypted Box<$E>($name).', - error: e, - stackTrace: stack, - name: _logName, + e, + stack, ); rethrow; } @@ -194,9 +185,8 @@ class Vault { Future> openLazyBox( String name, ) async { - log( + _logger.info( 'Opening lazy box $name', - name: _logName, ); await applyAutolock(); @@ -212,11 +202,10 @@ class Vault { encryptionCipher: await encryptionCipher, ); } catch (e, stack) { - log( + _logger.severe( 'Failed to open Hive encrypted Lazy Box<$E>($name).', - error: e, - stackTrace: stack, - name: _logName, + e, + stack, ); rethrow; } @@ -224,18 +213,16 @@ class Vault { Future applyAutolock() async { if (shouldBeLocked == null || await shouldBeLocked!() == false) return; - log( + _logger.info( 'Apply autolock to Vault.', - name: _logName, ); await lock(); } Future ensureVaultIsUnlocked() async { if (!isLocked.value) { - log( + _logger.info( 'Vault already unlocked.', - name: _logName, ); return; @@ -246,9 +233,8 @@ class Vault { 'Vault.passwordDelegate must be set before opening Boxes.', ); } - log( + _logger.info( 'Requesting user action to unlock', - name: _logName, ); final passphrase = await passphraseDelegate!(); diff --git a/lib/infrastructure/rpc/awc_json_rpc_server.dart b/lib/infrastructure/rpc/awc_json_rpc_server.dart index ef737dd7a..369687220 100644 --- a/lib/infrastructure/rpc/awc_json_rpc_server.dart +++ b/lib/infrastructure/rpc/awc_json_rpc_server.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:developer'; import 'package:aewallet/domain/rpc/subscription.dart'; import 'package:aewallet/infrastructure/rpc/add_service/command_handler.dart'; @@ -18,6 +17,7 @@ import 'package:aewallet/infrastructure/rpc/sign_transactions/command_handler.da import 'package:aewallet/infrastructure/rpc/sub_account/command_handler.dart'; import 'package:aewallet/infrastructure/rpc/sub_current_account/command_handler.dart'; import 'package:json_rpc_2/json_rpc_2.dart'; +import 'package:logging/logging.dart'; import 'package:stream_channel/stream_channel.dart'; class AWCJsonRPCServer { @@ -85,7 +85,7 @@ class AWCJsonRPCServer { ); } - static const logName = 'RPC Server'; + static final _logger = Logger('RPC Server'); final StreamChannel channel; late final SubscribablePeer _peer; @@ -101,10 +101,9 @@ class AWCJsonRPCServer { return result.map( success: commandHandler.resultFromModel, failure: (failure) { - log( + _logger.info( 'Command failed', - name: logName, - error: failure, + failure, ); throw RpcException( @@ -137,11 +136,7 @@ class AWCJsonRPCServer { ); }, failure: (failure) { - log( - 'Command failed', - name: logName, - error: failure, - ); + _logger.severe('Command failed', failure); throw RpcException( failure.code, diff --git a/lib/infrastructure/rpc/awc_webview.dart b/lib/infrastructure/rpc/awc_webview.dart index 42bb10d9e..202b7714e 100644 --- a/lib/infrastructure/rpc/awc_webview.dart +++ b/lib/infrastructure/rpc/awc_webview.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:developer'; import 'package:aewallet/infrastructure/rpc/awc_json_rpc_server.dart'; import 'package:aewallet/util/universal_platform.dart'; @@ -12,7 +11,7 @@ import 'package:stream_channel/stream_channel.dart'; class AWCWebview extends StatefulWidget { const AWCWebview({super.key, required this.uri}); - static const _logName = 'AWCWebview'; + static final _logger = Logger('AWCWebview'); static bool get isAvailable => UniversalPlatform.isMobile; @@ -80,7 +79,7 @@ class _AWCWebviewState extends State { ) async { if (_isMessageChannelReady) return; if (!await AWCWebview.isAWCSupported) { - log('AWC unsupported.', name: AWCWebview._logName); + AWCWebview._logger.info('AWC unsupported.'); return; } @@ -96,7 +95,7 @@ class _AWCWebviewState extends State { ) async { await controller.evaluateJavascript( source: """ -console.log("[AWC] Init webmessage"); +console.AWCWebview._logger.info("[AWC] Init webmessage"); var onAWCReady = (awc) => {}; var awcAvailable = true; var awc; @@ -104,7 +103,7 @@ window.addEventListener('message', function(event) { if (event.data == 'capturePort') { if (event.ports[0] != null) { awc = event.ports[0]; - console.log("[AWC] Init webmessage Done"); + console.AWCWebview._logger.info("[AWC] Init webmessage Done"); if (onAWCReady !== undefined) { onAWCReady(awc); } diff --git a/lib/infrastructure/rpc/deeplink_server.dart b/lib/infrastructure/rpc/deeplink_server.dart index 060beb444..286db094b 100644 --- a/lib/infrastructure/rpc/deeplink_server.dart +++ b/lib/infrastructure/rpc/deeplink_server.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:developer'; import 'package:aewallet/infrastructure/rpc/add_service/command_handler.dart'; import 'package:aewallet/infrastructure/rpc/dto/rpc_command_handler.dart'; @@ -13,6 +12,7 @@ import 'package:aewallet/infrastructure/rpc/refresh_current_account/command_hand import 'package:aewallet/infrastructure/rpc/send_transaction/command_handler.dart'; import 'package:aewallet/infrastructure/rpc/sign_transactions/command_handler.dart'; import 'package:deeplink_rpc/deeplink_rpc.dart'; +import 'package:logging/logging.dart'; class ArchethicDeeplinkRPCServer extends DeeplinkRpcRequestReceiver { ArchethicDeeplinkRPCServer() { @@ -112,17 +112,16 @@ class ArchethicDeeplinkRPCServer extends DeeplinkRpcRequestReceiver { RPCCommandHandler commandHandler, DeeplinkRpcRequest request, ) async { - const logName = 'DeeplinkRpcHandler'; + final _logger = Logger('DeeplinkRpcHandler'); final result = await commandHandler.handle(request.params); return result.map( success: commandHandler.resultFromModel, failure: (failure) { - log( + _logger.severe( 'Command failed', - name: logName, - error: failure, + failure, ); throw DeeplinkRpcFailure( diff --git a/lib/infrastructure/rpc/dto/rpc_command_handler.dart b/lib/infrastructure/rpc/dto/rpc_command_handler.dart index 5599fe8b7..1036065fa 100644 --- a/lib/infrastructure/rpc/dto/rpc_command_handler.dart +++ b/lib/infrastructure/rpc/dto/rpc_command_handler.dart @@ -1,5 +1,3 @@ -import 'dart:developer'; - import 'package:aewallet/domain/models/core/result.dart'; import 'package:aewallet/domain/rpc/command_dispatcher.dart'; import 'package:aewallet/domain/rpc/commands/command.dart'; @@ -7,6 +5,7 @@ import 'package:aewallet/domain/rpc/commands/failure.dart'; import 'package:aewallet/domain/rpc/subscription.dart'; import 'package:aewallet/infrastructure/rpc/dto/rpc_request.dart'; import 'package:aewallet/util/get_it_instance.dart'; +import 'package:logging/logging.dart'; /// [RPCCommandHandler] is responsible for converting /// data between RPC channel (deeplink, websocket ...) DTOs @@ -20,8 +19,8 @@ abstract class RPCCommandHandler { Map resultFromModel(covariant R model); Future> handle(Map data) async { - final logName = 'RPCCommandHandler [$runtimeType]'; - log('Received command', name: logName); + final _logger = Logger('RPCCommandHandler [$runtimeType]') + ..info('Received command'); try { final requestDTO = RPCRequestDTO.fromJson( @@ -35,12 +34,7 @@ abstract class RPCCommandHandler { return sl.get().add(commandModel); // ignore: avoid_catching_errors } on TypeError catch (e, stack) { - log( - 'Invalid data', - name: logName, - error: e, - stackTrace: stack, - ); + _logger.severe('Invalid data', e, stack); return Result.failure(RPCFailure.invalidParams()); } } diff --git a/lib/infrastructure/rpc/websocket_server.dart b/lib/infrastructure/rpc/websocket_server.dart index c508ed4f9..1b0a60cdf 100644 --- a/lib/infrastructure/rpc/websocket_server.dart +++ b/lib/infrastructure/rpc/websocket_server.dart @@ -1,15 +1,15 @@ import 'dart:async'; -import 'dart:developer'; import 'dart:io'; import 'package:aewallet/infrastructure/rpc/awc_json_rpc_server.dart'; import 'package:aewallet/util/universal_platform.dart'; +import 'package:logging/logging.dart'; import 'package:web_socket_channel/io.dart'; class ArchethicWebsocketRPCServer { ArchethicWebsocketRPCServer(); - static const logName = 'Websocket RPC Server'; + static final _logger = Logger('Websocket RPC Server'); static const host = '127.0.0.1'; static const port = 12345; @@ -23,11 +23,11 @@ class ArchethicWebsocketRPCServer { Future run() async => runZonedGuarded( () async { if (isRunning) { - log('Already running. Cancel `start`', name: logName); + _logger.info('Already running. Cancel `start`'); return; } - log('Starting at ws://$host:$port', name: logName); + _logger.info('Starting at ws://$host:$port'); final httpServer = await HttpServer.bind( host, port, @@ -35,7 +35,7 @@ class ArchethicWebsocketRPCServer { ); httpServer.listen((HttpRequest request) async { - log('Received connection', name: logName); + _logger.info('Received connection'); final socket = await WebSocketTransformer.upgrade(request); final channel = IOWebSocketChannel(socket); @@ -48,40 +48,30 @@ class ArchethicWebsocketRPCServer { _runningHttpServer = httpServer; }, (error, stack) { - log( - 'WebSocket server failed', - error: error, - stackTrace: stack, - name: logName, - ); + _logger.severe('WebSocket server failed', error, stack); }, ); Future stop() async => runZonedGuarded( () async { if (!isRunning) { - log('Already stopped. Cancel `stop`', name: logName); + _logger.info('Already stopped. Cancel `stop`'); return; } - log('Closing all websocket connections', name: logName); + _logger.info('Closing all websocket connections'); for (final socket in _openedSockets) { await socket.close(); } _openedSockets.clear(); - log('Stopping at ws://$host:$port', name: logName); + _logger.info('Stopping at ws://$host:$port'); await _runningHttpServer?.close(); _runningHttpServer = null; - log('Server stopped at ws://$host:$port', name: logName); + _logger.info('Server stopped at ws://$host:$port'); }, (error, stack) { - log( - 'WebSocket server failed to stop', - error: error, - stackTrace: stack, - name: logName, - ); + _logger.severe('WebSocket server failed to stop', error, stack); }, ); } diff --git a/lib/local_data_migration_widget.dart b/lib/local_data_migration_widget.dart index 9197066ac..a5365a718 100644 --- a/lib/local_data_migration_widget.dart +++ b/lib/local_data_migration_widget.dart @@ -1,17 +1,18 @@ -import 'dart:developer'; - import 'package:aewallet/ui/widgets/components/sheet_skeleton.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/localizations.dart'; +import 'package:logging/logging.dart'; class LocalDataMigrationWidget extends StatelessWidget { const LocalDataMigrationWidget({ super.key, }); + static final _logger = Logger('DataMigration'); + @override Widget build(BuildContext context) { - log('Migration in progress Widget', name: 'DataMigration'); + _logger.info('Migration in progress Widget'); return SheetSkeleton( appBar: AppBar(), menu: true, diff --git a/lib/main.dart b/lib/main.dart index 7901f2b5c..929f0aec3 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,7 +1,6 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:async'; -import 'dart:developer' as dev; import 'dart:io'; import 'package:aewallet/application/authentication/authentication.dart'; @@ -34,6 +33,7 @@ import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_native_splash/flutter_native_splash.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import 'package:logging/logging.dart'; import 'package:oktoast/oktoast.dart'; import 'package:window_manager/window_manager.dart'; @@ -120,6 +120,7 @@ class AppState extends ConsumerState with WidgetsBindingObserver { static final GlobalKey rootNavigatorKey = GlobalKey(); final router = RoutesPath(rootNavigatorKey).createRouter(); + final _logger = Logger('AppWidget'); @override void initState() { @@ -139,7 +140,7 @@ class AppState extends ConsumerState with WidgetsBindingObserver { } Future didChangeAppLifecycleStateAsync(AppLifecycleState state) async { - dev.log('Lifecycle State : $state'); + _logger.info('Lifecycle State : $state'); var isDeviceSecured = false; ref.invalidate(ArchethicOracleUCOProviders.archethicOracleUCO); await ref @@ -243,7 +244,7 @@ class Splash extends ConsumerStatefulWidget { } class SplashState extends ConsumerState with WidgetsBindingObserver { - // late bool _hasCheckedLoggedIn; + final _logger = Logger('SplashState'); Future initializeProviders() async { final locale = ref.read(LanguageProviders.selectedLocale); @@ -297,7 +298,7 @@ class SplashState extends ConsumerState with WidgetsBindingObserver { context.go(HomePage.routerPage); } catch (e, stack) { - dev.log(e.toString(), error: e, stackTrace: stack); + _logger.severe(e.toString(), e, stack); context.go(IntroWelcome.routerPage); } } diff --git a/lib/providers_observer.dart b/lib/providers_observer.dart index a3b8c1b22..8caff9de0 100644 --- a/lib/providers_observer.dart +++ b/lib/providers_observer.dart @@ -1,6 +1,5 @@ -import 'dart:developer'; - import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:logging/logging.dart'; class ProvidersLogger extends ProviderObserver { @override @@ -10,7 +9,7 @@ class ProvidersLogger extends ProviderObserver { ProviderContainer container, ) { if (provider.name != null) { - log('didAddProvider($value)', name: '${provider.name}'); + Logger(provider.name!).info('didAddProvider($value)'); } } @@ -22,7 +21,7 @@ class ProvidersLogger extends ProviderObserver { ProviderContainer container, ) { if (provider.name != null) { - log('didUpdateProvider($newValue)', name: '${provider.name}'); + Logger(provider.name!).info('didUpdateProvider($newValue)'); } } @@ -34,14 +33,14 @@ class ProvidersLogger extends ProviderObserver { ProviderContainer container, ) { if (provider.name != null) { - log('providerDidFail($error)', name: '${provider.name}'); + Logger(provider.name!).info('providerDidFail($error)'); } } @override void didDisposeProvider(ProviderBase provider, ProviderContainer container) { if (provider.name != null) { - log('didDisposeProvider', name: '${provider.name}'); + Logger(provider.name!).info('didDisposeProvider'); } } } diff --git a/lib/service/app_service.dart b/lib/service/app_service.dart index 7505f44e8..55e291797 100644 --- a/lib/service/app_service.dart +++ b/lib/service/app_service.dart @@ -2,7 +2,6 @@ import 'dart:async'; import 'dart:convert'; -import 'dart:developer' as dev; import 'dart:math'; import 'dart:typed_data'; @@ -23,8 +22,11 @@ import 'package:aewallet/util/queue.dart'; import 'package:archethic_lib_dart/archethic_lib_dart.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; +import 'package:logging/logging.dart'; class AppService { + static final _logger = Logger('AppService'); + Future>> getTransactionChain( Map addresses, String? request, @@ -184,7 +186,7 @@ class AppService { ) { final recentTransactions = []; for (final transaction in transactionChain) { - dev.log('type ${transaction.type!} ${transaction.toJson()}'); + _logger.info('type ${transaction.type!} ${transaction.toJson()}'); if (transaction.type! == 'token') { final recentTransaction = RecentTransaction() ..address = transaction.address!.address @@ -275,34 +277,25 @@ class AppService { String address, int mostRecentTimestamp, ) async { + final _logger = Logger('AppService - recentTx'); + var newRecentTransactionList = recentTransactionList; - dev.log( - '>> START getTransaction : ${DateTime.now()}', - name: 'recentTx', - ); + _logger.info('>> START getTransaction : ${DateTime.now()}'); final transaction = await sl.get().getTransaction( [address], request: 'address, type, chainLength, validationStamp { timestamp, ledgerOperations { fee } }, data { actionRecipients { action, address, args } ledger { uco { transfers { amount, to } } token {transfers {amount, to, tokenAddress, tokenId } } } }', ); - dev.log('$transaction'); - dev.log( - '>> END getTransaction : ${DateTime.now()}', - name: 'recentTx', - ); - dev.log( - '>> START getTransactionInputs : ${DateTime.now()}', - name: 'recentTx', - ); + _logger + ..info('$transaction') + ..info('>> END getTransaction : ${DateTime.now()}') + ..info('>> START getTransactionInputs : ${DateTime.now()}'); final transactionInputs = await sl.get().getTransactionInputs( [address], request: 'from, spent, tokenAddress, tokenId, amount, timestamp', limit: 10, ); - dev.log( - '>> END getTransactionInputs : ${DateTime.now()}', - name: 'recentTx', - ); + _logger.info('>> END getTransactionInputs : ${DateTime.now()}'); if (transaction[address] != null) { final transactionTimeStamp = transaction[address]!.validationStamp!.timestamp!; @@ -320,10 +313,11 @@ class AppService { ..sort((tx1, tx2) => tx1.timestamp!.compareTo(tx2.timestamp!)); } - dev.log('1) $transactionInputs'); - dev.log( - 'transactionTimeStamp $transactionTimeStamp > mostRecentTimestamp $mostRecentTimestamp)', - ); + _logger + ..info('1) $transactionInputs') + ..info( + 'transactionTimeStamp $transactionTimeStamp > mostRecentTimestamp $mostRecentTimestamp)', + ); if (transactionTimeStamp > mostRecentTimestamp) { newRecentTransactionList ..addAll( @@ -351,9 +345,8 @@ class AppService { KeychainSecuredInfos keychainSecuredInfos, List localRecentTransactionList, ) async { - dev.log( + _logger.info( '>> START getRecentTransactions : ${DateTime.now()}', - name: 'recentTx', ); // get the most recent movement in cache @@ -371,7 +364,7 @@ class AppService { final lastIndex = await sl.get().getTransactionIndex( [lastAddress], ); - dev.log('lastAddress : $lastAddress -> lastIndex: $lastIndex'); + _logger.info('lastAddress : $lastAddress -> lastIndex: $lastIndex'); var index = lastIndex[lastAddress] ?? 0; String addressToSearch; var iterMax = 10; @@ -384,12 +377,12 @@ class AppService { index: index, ), ); - dev.log('addressToSearch : $addressToSearch'); + _logger.info('addressToSearch : $addressToSearch'); if (localRecentTransactionList.any( (element) => element.address!.toUpperCase() == addressToSearch.toUpperCase(), )) { - dev.log('addressToSearch exists in local -> break'); + _logger.info('addressToSearch exists in local -> break'); if (addressToSearch.toUpperCase() == lastAddress.toUpperCase()) { recentTransactions = await _buildRecentTransactionFromTransaction( recentTransactions, @@ -628,9 +621,8 @@ class AppService { recentTransactions: recentTransactions, ); - dev.log( + _logger.info( '>> END getRecentTransactions : ${DateTime.now()}', - name: 'recentTx', ); return recentTransactions; @@ -735,7 +727,7 @@ class AppService { } Future> getFungiblesTokensList(String address) async { - dev.log( + _logger.info( '>> START getFungiblesTokensList : ${DateTime.now()}', ); @@ -811,7 +803,7 @@ class AppService { (a, b) => a.tokenInformation!.name!.compareTo(b.tokenInformation!.name!), ); - dev.log( + _logger.info( '>> END getFungiblesTokensList : ${DateTime.now()}', ); @@ -1146,7 +1138,7 @@ class AppService { transactionFee = await sl.get().getTransactionFee(transaction); } catch (e, stack) { - dev.log('Failed to get transaction fees', error: e, stackTrace: stack); + _logger.severe('Failed to get transaction fees', e, stack); } return fromBigInt(transactionFee.fee).toDouble(); } diff --git a/lib/ui/views/authenticate/auto_lock_guard.dart b/lib/ui/views/authenticate/auto_lock_guard.dart index 34b434bfb..2b41a4d87 100644 --- a/lib/ui/views/authenticate/auto_lock_guard.dart +++ b/lib/ui/views/authenticate/auto_lock_guard.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:developer'; import 'package:aewallet/application/authentication/authentication.dart'; import 'package:aewallet/application/settings/settings.dart'; @@ -22,6 +21,7 @@ import 'package:flutter_gen/gen_l10n/localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_vibrate/flutter_vibrate.dart'; import 'package:lit_starfield/lit_starfield.dart'; +import 'package:logging/logging.dart'; part 'components/lock_mask_screen.dart'; part 'countdown_lock_screen.dart'; @@ -49,7 +49,7 @@ class _AutoLockGuardState extends ConsumerState with WidgetsBindingObserver { RestartableTimer? timer; - static const _logName = 'AuthenticationGuard-Widget'; + static final _logger = Logger('AuthenticationGuard-Widget'); @override Widget build(BuildContext context) { @@ -81,9 +81,8 @@ class _AutoLockGuardState extends ConsumerState @override void initState() { super.initState(); - log( + _logger.info( 'Init state', - name: _logName, ); WidgetsBinding.instance.addObserver(this); @@ -110,9 +109,8 @@ class _AutoLockGuardState extends ConsumerState @override void didChangeAppLifecycleState(AppLifecycleState state) { - log( + _logger.info( 'AppLifecycleState : $state', - name: _logName, ); switch (state) { case AppLifecycleState.resumed: @@ -135,14 +133,14 @@ class _AutoLockGuardState extends ConsumerState } void _unscheduleLock() { - log('Unschedule lock', name: _logName); + _logger.info('Unschedule lock'); timer?.cancel(); timer = null; } void _scheduleLock(Duration durationBeforeLock) { - log('Schedule lock in $durationBeforeLock', name: _logName); + _logger.info('Schedule lock in $durationBeforeLock'); timer?.cancel(); timer = RestartableTimer( durationBeforeLock, @@ -175,7 +173,7 @@ class _AutoLockGuardState extends ConsumerState } Future _shouldBeLocked() async { - log('Check if vault should be locked', name: _logName); + _logger.info('Check if vault should be locked'); final value = await ref.read( AuthenticationProviders.authenticationGuard.future, ); @@ -188,24 +186,21 @@ class _AutoLockGuardState extends ConsumerState } final durationBeforeLock = lockDate.difference(DateTime.now()); - log( + _logger.info( 'Duration before lock : $durationBeforeLock', - name: _logName, ); return durationBeforeLock <= Duration.zero; } static Completer? _forceAuthenticationCompleter; Future _forceAuthent() async { - log( + _logger.info( 'Force authent', - name: _logName, ); if (_forceAuthenticationCompleter != null) { - log( + _logger.info( '... authent already running.', - name: _logName, ); return _forceAuthenticationCompleter!.future; diff --git a/lib/ui/views/authenticate/components/lock_overlay.mixin.dart b/lib/ui/views/authenticate/components/lock_overlay.mixin.dart index 2af58c961..0c7f308b2 100644 --- a/lib/ui/views/authenticate/components/lock_overlay.mixin.dart +++ b/lib/ui/views/authenticate/components/lock_overlay.mixin.dart @@ -1,19 +1,18 @@ -import 'dart:developer'; - import 'package:flutter/material.dart'; +import 'package:logging/logging.dart'; mixin LockOverlayMixin { Widget get child; OverlayEntry? _overlayEntry; - static const _logName = 'LockOverlay'; + static final _logger = Logger('LockOverlay'); bool get isVisible => _overlayEntry != null; void show(BuildContext context) { - log('Show', name: _logName); + _logger.info('Show'); if (_overlayEntry != null) { - log('... already visible. Abort', name: _logName); + _logger.info('... already visible. Abort'); return; } @@ -24,9 +23,9 @@ mixin LockOverlayMixin { } void hide() { - log('Hide', name: _logName); + _logger.info('Hide'); if (_overlayEntry == null) { - log('... not visible. Abort', name: _logName); + _logger.info('... not visible. Abort'); return; } diff --git a/lib/ui/views/authenticate/countdown_lock_screen.dart b/lib/ui/views/authenticate/countdown_lock_screen.dart index 3093ee68d..b51a0756a 100644 --- a/lib/ui/views/authenticate/countdown_lock_screen.dart +++ b/lib/ui/views/authenticate/countdown_lock_screen.dart @@ -2,7 +2,7 @@ part of 'auto_lock_guard.dart'; /// Handles navigation to the lock screen mixin CountdownLockMixin { - static const _logName = 'AuthenticationGuard-Mixin'; + static final _logger = Logger('AuthenticationGuard-Mixin'); /// Displays lock screen (with the timer) if /// application should be locked (too much authentication failures). @@ -16,7 +16,7 @@ mixin CountdownLockMixin { AuthenticationProviders.isLockCountdownRunning.future, ); if (shouldLock) { - log('Show countdown screen', name: _logName); + _logger.info('Show countdown screen'); CountdownLockOverlay.instance().show(context); } } diff --git a/lib/ui/views/authenticate/logging_out.dart b/lib/ui/views/authenticate/logging_out.dart index d1a4ebacd..5f43f52c1 100644 --- a/lib/ui/views/authenticate/logging_out.dart +++ b/lib/ui/views/authenticate/logging_out.dart @@ -1,7 +1,5 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later -import 'dart:developer'; - import 'package:aewallet/application/session/session.dart'; import 'package:aewallet/main.dart'; import 'package:aewallet/ui/widgets/components/show_sending_animation.dart'; @@ -9,6 +7,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; +import 'package:logging/logging.dart'; class LoggingOutScreen extends ConsumerStatefulWidget { const LoggingOutScreen({ @@ -23,16 +22,18 @@ class LoggingOutScreen extends ConsumerStatefulWidget { } class _LoggingOutScreenState extends ConsumerState { + static final _logger = Logger('LoggingOutScreen'); + @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) async { - log('Logging out'); + _logger.info('Logging out'); await Future.wait([ Future.delayed(const Duration(seconds: 2)), ref.read(SessionProviders.session.notifier).logout(), ]); - log('Logged out'); + _logger.info('Logged out'); context.go(Splash.routerPage); }); } diff --git a/lib/ui/views/intro/layouts/intro_import_seed.dart b/lib/ui/views/intro/layouts/intro_import_seed.dart index 33815aa81..1a12e1359 100755 --- a/lib/ui/views/intro/layouts/intro_import_seed.dart +++ b/lib/ui/views/intro/layouts/intro_import_seed.dart @@ -1,7 +1,6 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:async'; -import 'dart:developer'; import 'dart:ui'; import 'package:aewallet/application/account/providers.dart'; @@ -34,6 +33,7 @@ import 'package:flutter_gen/gen_l10n/localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_vibrate/flutter_vibrate.dart'; import 'package:go_router/go_router.dart'; +import 'package:logging/logging.dart'; import 'package:material_symbols_icons/symbols.dart'; import 'package:unorm_dart/unorm_dart.dart' as unorm; @@ -48,6 +48,8 @@ class IntroImportSeedPage extends ConsumerStatefulWidget { class _IntroImportSeedState extends ConsumerState implements SheetSkeletonInterface { + final _logger = Logger('IntroImportSeed'); + bool _mnemonicIsValid = false; String _mnemonicError = ''; bool? isPressed; @@ -512,9 +514,7 @@ class _IntroImportSeedState extends ConsumerState key: Key('accountName${account.nameDisplayed}'), ), ); - log( - '<>', - ); + _logger.info('<>'); } } diff --git a/lib/ui/views/nft/layouts/components/thumbnail/nft_thumbnail_image.dart b/lib/ui/views/nft/layouts/components/thumbnail/nft_thumbnail_image.dart index 7356544cf..4107426b4 100644 --- a/lib/ui/views/nft/layouts/components/thumbnail/nft_thumbnail_image.dart +++ b/lib/ui/views/nft/layouts/components/thumbnail/nft_thumbnail_image.dart @@ -1,7 +1,5 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later -import 'dart:developer' as dev; - import 'package:aewallet/ui/views/nft/layouts/components/thumbnail/nft_thumbnail_error.dart'; import 'package:aewallet/ui/views/nft/layouts/components/thumbnail/nft_thumbnail_loading.dart'; import 'package:aewallet/util/cache_manager_hive.dart'; @@ -11,6 +9,7 @@ import 'package:aewallet/util/universal_platform.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/localizations.dart'; +import 'package:logging/logging.dart'; class NFTThumbnailImage extends StatefulWidget { const NFTThumbnailImage({ @@ -30,6 +29,7 @@ class NFTThumbnailImage extends StatefulWidget { class NFTThumbnailImageState extends State with AutomaticKeepAliveClientMixin { + final _logger = Logger('NFTThumbnailImage'); @override bool get wantKeepAlive { return true; @@ -53,18 +53,16 @@ class NFTThumbnailImageState extends State ), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasError) { - dev.log( + _logger.info( '${widget.address} Error ${DateTime.now().toUtc()}', - name: 'NFTThumbnailImage', ); return NFTThumbnailError( message: localizations.previewNotAvailable, ); } if (snapshot.hasData) { - dev.log( + _logger.info( '${widget.address} Data ${DateTime.now().toUtc()}', - name: 'NFTThumbnailImage', ); return widget.roundBorder == true ? ClipRRect( @@ -77,9 +75,8 @@ class NFTThumbnailImageState extends State snapshot.data!, ); } else { - dev.log( + _logger.info( '${widget.address} Loading ${DateTime.now().toUtc()}', - name: 'NFTThumbnailImage', ); return const NFTThumbnailLoading(); } @@ -94,10 +91,10 @@ Future _getImageFromToken( String address, Map properties, ) async { - dev.log( - 'start _getImageFromToken ${DateTime.now().toUtc()}', - name: 'cacheManagement', - ); + final _logger = Logger('cacheManagement') + ..info( + 'start _getImageFromToken ${DateTime.now().toUtc()}', + ); if (UniversalPlatform.isAndroid || UniversalPlatform.isIOS || @@ -106,43 +103,40 @@ Future _getImageFromToken( final cacheItem = cacheManagerHive.get(address); if (cacheItem != null) { - dev.log('Use cache for token $address', name: 'cacheManagement'); - dev.log( - 'end _getImageFromToken ${DateTime.now().toUtc()}', - name: 'cacheManagement', - ); + _logger + ..info('Use cache for token $address') + ..info( + 'end _getImageFromToken ${DateTime.now().toUtc()}', + ); return cacheItem; } else { - dev.log('No cache for token $address', name: 'cacheManagement'); + _logger.info('No cache for token $address'); final imageBytes = await TokenUtil.getImageFromToken( properties, ); if (imageBytes == null) { - dev.log( + _logger.info( 'end _getImageFromToken ${DateTime.now().toUtc()}', - name: 'cacheManagement', ); return Uint8List.fromList([]); } - dev.log('Add cache for token $address', name: 'cacheManagement'); + _logger.info('Add cache for token $address'); await cacheManagerHive.put( address, CacheItemHive(imageBytes), ); - dev.log( + _logger.info( 'end _getImageFromToken ${DateTime.now().toUtc()}', - name: 'cacheManagement', ); return imageBytes; } } else { - dev.log('No cache for token $address', name: 'cacheManagement'); + _logger.info('No cache for token $address'); final imageBytes = await TokenUtil.getImageFromToken( properties, ); - dev.log( + _logger.info( 'end _getImageFromToken ${DateTime.now().toUtc()}', - name: 'cacheManagement', ); return imageBytes!; } diff --git a/lib/ui/views/sheets/ledger_sheet.dart b/lib/ui/views/sheets/ledger_sheet.dart index 116b6418c..31eb17e40 100755 --- a/lib/ui/views/sheets/ledger_sheet.dart +++ b/lib/ui/views/sheets/ledger_sheet.dart @@ -1,7 +1,5 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later -import 'dart:developer'; - import 'package:aewallet/ui/themes/styles.dart'; // Project imports: @@ -19,6 +17,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:ledger_dart_lib/ledger_dart_lib.dart'; +import 'package:logging/logging.dart'; /*final getArchAddress = transport( 0xe0, @@ -51,6 +50,7 @@ class _LedgerSheetState extends ConsumerState { String labelResponse = ''; String info = ''; String method = ''; + final _logger = Logger('LedgerSheet'); void update() { setState(() { @@ -236,7 +236,8 @@ class _LedgerSheetState extends ConsumerState { hex.decode(enterPayloadController!.text), ), ); - log('getArchAddress: ${uint8ListToHex(getArchAddress)}'); + _logger.info( + 'getArchAddress: ${uint8ListToHex(getArchAddress)}'); await sl .get() .connectLedger(getArchAddress); diff --git a/lib/ui/views/transactions/transaction_infos_sheet.dart b/lib/ui/views/transactions/transaction_infos_sheet.dart index 36b96e232..9570f1429 100755 --- a/lib/ui/views/transactions/transaction_infos_sheet.dart +++ b/lib/ui/views/transactions/transaction_infos_sheet.dart @@ -1,7 +1,5 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later -import 'dart:developer'; - import 'package:aewallet/application/account/providers.dart'; import 'package:aewallet/application/contact.dart'; import 'package:aewallet/application/session/session.dart'; @@ -27,6 +25,7 @@ import 'package:flutter_gen/gen_l10n/localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import 'package:intl/intl.dart'; +import 'package:logging/logging.dart'; class TransactionInfosSheet extends ConsumerStatefulWidget { const TransactionInfosSheet(this.notificationRecipientAddress, {super.key}); @@ -177,6 +176,8 @@ class _TransactionBuildInfos extends ConsumerWidget { final TransactionInfos transactionInfo; + static final _logger = Logger('TransactionBuildInfos'); + @override Widget build(BuildContext context, WidgetRef ref) { final preferences = ref.watch(SettingsProviders.settings); @@ -301,7 +302,7 @@ class _TransactionBuildInfos extends ConsumerWidget { ) { if (transactionInfo.domain == 'UCOLedger' && transactionInfo.titleInfo == 'To') { - log('transactionInfo.valueInfo: ${transactionInfo.valueInfo}'); + _logger.info('transactionInfo.valueInfo: ${transactionInfo.valueInfo}'); return ref .watch( ContactProviders.getContactWithAddress(transactionInfo.valueInfo), @@ -309,13 +310,17 @@ class _TransactionBuildInfos extends ConsumerWidget { .map( data: (data) { if (data.value == null) { - log('transactionInfo.valueInfo: ${transactionInfo.valueInfo} : data null'); + _logger.info( + 'transactionInfo.valueInfo: ${transactionInfo.valueInfo} : data null', + ); return SelectableText( transactionInfo.valueInfo, style: ArchethicThemeStyles.textStyleSize14W200Primary, ); } else { - log('transactionInfo.valueInfo: ${transactionInfo.valueInfo} : data not null'); + _logger.info( + 'transactionInfo.valueInfo: ${transactionInfo.valueInfo} : data not null', + ); return SelectableText( data.value!.format, style: ArchethicThemeStyles.textStyleSize14W200Primary, diff --git a/lib/util/cache_manager_hive.dart b/lib/util/cache_manager_hive.dart index 393302b0f..6343bd309 100644 --- a/lib/util/cache_manager_hive.dart +++ b/lib/util/cache_manager_hive.dart @@ -1,10 +1,9 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later -import 'dart:developer'; - import 'package:aewallet/infrastructure/datasources/appdb.hive.dart'; import 'package:aewallet/infrastructure/datasources/vault/vault.dart'; import 'package:hive/hive.dart'; +import 'package:logging/logging.dart'; part 'cache_manager_hive.g.dart'; @@ -33,6 +32,8 @@ class CacheManagerHive { final Box _cacheBox; final int maxCacheItems; + final _logger = Logger('cacheManagerHive'); + static CacheManagerHive? _instance; static Future getInstance() async { if (_instance?._cacheBox.isOpen == true) return _instance!; @@ -47,7 +48,7 @@ class CacheManagerHive { Future put(String key, CacheItemHive cacheItemHive) async { if (_cacheBox.length >= maxCacheItems) { - log('Remove oldest item', name: 'cacheManagerHive'); + _logger.info('Remove oldest item'); _removeOldestItem(); } await _cacheBox.put(key, cacheItemHive); @@ -65,7 +66,7 @@ class CacheManagerHive { if (DateTime.now().isBefore(ttlExpirationTime)) { return cachedItem.value; } else { - log('Delete expired item $key', name: 'cacheManagerHive'); + _logger.info('Delete expired item $key'); _cacheBox.delete(key); } } else { diff --git a/lib/util/keychain_util.dart b/lib/util/keychain_util.dart index b0d184aef..321b798a8 100644 --- a/lib/util/keychain_util.dart +++ b/lib/util/keychain_util.dart @@ -1,7 +1,6 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:async'; -import 'dart:developer' as dev; import 'dart:math'; import 'dart:typed_data'; @@ -22,10 +21,13 @@ import 'package:aewallet/service/app_service.dart'; import 'package:aewallet/util/get_it_instance.dart'; import 'package:archethic_lib_dart/archethic_lib_dart.dart'; import 'package:event_taxi/event_taxi.dart'; +import 'package:logging/logging.dart'; class KeychainUtil with KeychainServiceMixin { final appWalletDatasource = AppWalletHiveDatasource.instance(); + final _logger = Logger('KeychainUtil'); + Future createKeyChainAccess( NetworksSetting networkSettings, String? seed, @@ -52,7 +54,7 @@ class KeychainUtil with KeychainServiceMixin { apiService: sl.get(), ); - dev.log('>>> Create access <<< ${accessKeychainTx.address}'); + _logger.info('>>> Create access <<< ${accessKeychainTx.address}'); await transactionSender.send( transaction: accessKeychainTx, onConfirmation: (event) async { @@ -129,7 +131,7 @@ class KeychainUtil with KeychainServiceMixin { apiService: sl.get(), ); - dev.log('>>> Create keychain <<< ${keychainTransaction.address}'); + _logger.info('>>> Create keychain <<< ${keychainTransaction.address}'); await transactionSender.send( transaction: keychainTransaction, onConfirmation: (event) async { diff --git a/lib/util/ledger/archethic_ledger_util.dart b/lib/util/ledger/archethic_ledger_util.dart index bbdfca62c..847f67841 100644 --- a/lib/util/ledger/archethic_ledger_util.dart +++ b/lib/util/ledger/archethic_ledger_util.dart @@ -1,13 +1,14 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later -// Dart imports: -import 'dart:developer'; import 'dart:typed_data'; // Package imports: import 'package:archethic_lib_dart/archethic_lib_dart.dart'; import 'package:convert/convert.dart'; import 'package:ledger_dart_lib/ledger_dart_lib.dart'; +import 'package:logging/logging.dart'; + +final _logger = Logger('LedgerUtils'); Uint8List getSignTxnAPDU( OnChainWalletData onChainWalletData, @@ -19,7 +20,7 @@ Uint8List getSignTxnAPDU( hexToUint8List(onChainWalletData.encodedWalletKey!), hexToUint8List(onChainWalletData.encryptedWallet!), ]); - log(uint8ListToHex(transaction.originSignaturePayload())); + _logger.info(uint8ListToHex(transaction.originSignaturePayload())); payload = concatUint8List([transaction.originSignaturePayload(), payload]); final payloadLength = hexToUint8List(payload.lengthInBytes.toRadixString(16)); final signPayload = concatUint8List([payloadLength, payload]); diff --git a/lib/util/logger.dart b/lib/util/logger.dart index 2272118a6..3ae7b55ce 100644 --- a/lib/util/logger.dart +++ b/lib/util/logger.dart @@ -10,8 +10,6 @@ class LoggerSetup { static LoggerSetup? _instance; - List> _subscriptions = []; - Future setup() async { Logger.root.level = kDebugMode ? Level.ALL : Level.INFO; @@ -23,23 +21,18 @@ class LoggerSetup { } Future _registerLogListeners() async { - for (final subscription in _subscriptions) { - await subscription.cancel(); - } - _subscriptions = []; + Logger.root.clearListeners(); if (kIsWeb) { - _subscriptions.add( - Logger.root.onRecord.listen((event) { - debugPrint('[${event.loggerName}] ${event.message}'); - if (event.error != null) { - debugPrint('\t${event.error}'); - } - if (event.stackTrace != null) { - debugPrint('\t${event.stackTrace}'); - } - }), - ); + Logger.root.onRecord.listen((event) { + debugPrint('[${event.loggerName}] ${event.message}'); + if (event.error != null) { + debugPrint('\t${event.error}'); + } + if (event.stackTrace != null) { + debugPrint('\t${event.stackTrace}'); + } + }); } if (!kIsWeb) { diff --git a/lib/util/user_data_util.dart b/lib/util/user_data_util.dart index b9c56d812..b84c14659 100644 --- a/lib/util/user_data_util.dart +++ b/lib/util/user_data_util.dart @@ -1,7 +1,6 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:async'; -import 'dart:developer' as dev; import 'package:aewallet/ui/themes/archethic_theme.dart'; import 'package:aewallet/ui/util/ui_util.dart'; @@ -12,6 +11,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_gen/gen_l10n/localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:logging/logging.dart'; import 'package:quiver/strings.dart'; import 'package:validators/validators.dart'; @@ -29,6 +29,8 @@ class QRScanErrs { } class UserDataUtil { + static final _logger = Logger('UserDataUtil'); + static String? _parseData(String data, DataType type) { final dataTrim = data.trim(); if (type == DataType.raw) { @@ -96,7 +98,7 @@ class UserDataUtil { } on FormatException { return QRScanErrs.cancelError; } catch (e, stack) { - dev.log('Unknown QR Scan Error', error: e, stackTrace: stack); + _logger.severe('Unknown QR Scan Error', e, stack); return QRScanErrs.unknownError; } }