From 202aaa61d2053ecad73cddbb8c72e4532eb168b9 Mon Sep 17 00:00:00 2001 From: Ademar Alves de Oliveira Date: Thu, 5 Oct 2023 17:10:00 -0300 Subject: [PATCH 1/4] Change the log library from fimber to logging --- lib/app_config.dart | 6 +- lib/background/background_task_handler.dart | 6 +- lib/background/breez_message_handler.dart | 6 +- lib/bloc/account/account_bloc.dart | 56 ++++----- lib/bloc/account/credentials_manager.dart | 8 +- lib/bloc/backup/backup_bloc.dart | 12 +- .../buy_bitcoin/moonpay/moonpay_bloc.dart | 22 ++-- lib/bloc/connectivity/connectivity_bloc.dart | 12 +- lib/bloc/csv_exporter.dart | 24 ++-- lib/bloc/fee_options/fee_options_bloc.dart | 18 +-- lib/bloc/input/input_bloc.dart | 36 +++--- lib/bloc/network/network_settings_bloc.dart | 28 ++--- .../payment_options/payment_options_bloc.dart | 16 +-- lib/bloc/refund/refund_bloc.dart | 10 +- .../rev_swap_in_progress_bloc.dart | 12 +- lib/bloc/reverse_swap/reverse_swap_bloc.dart | 10 +- lib/bloc/security/security_bloc.dart | 6 +- .../swap_in_progress_bloc.dart | 12 +- lib/bloc/sweep/sweep_bloc.dart | 8 +- lib/bloc/user_profile/user_profile_bloc.dart | 20 +-- lib/config.dart | 24 ++-- lib/handlers/connectivity_handler.dart | 8 +- lib/handlers/input_handler.dart | 24 ++-- lib/handlers/payment_result_handler.dart | 12 +- lib/logger.dart | 114 ++++++++---------- lib/main.dart | 6 +- lib/models/payment_minutiae.dart | 14 +-- .../buy_bitcoin/moonpay/moonpay_webview.dart | 16 +-- .../create_invoice/create_invoice_page.dart | 12 +- lib/routes/create_invoice/qr_code_dialog.dart | 8 +- .../widgets/expiry_and_fee_message.dart | 4 +- lib/routes/dev/command_line_interface.dart | 16 +-- lib/routes/home/account_page.dart | 6 +- .../enter_payment_info_dialog.dart | 8 +- .../payment_filter_exporter.dart | 6 +- .../payments_list/payment_details_dialog.dart | 6 +- lib/routes/home/widgets/qr_action_button.dart | 8 +- .../initial_walkthrough.dart | 14 +-- lib/routes/lnurl/auth/lnurl_auth_handler.dart | 16 +-- lib/routes/lnurl/lnurl_invoice_delegate.dart | 18 +-- .../lnurl/payment/lnurl_payment_dialog.dart | 6 +- .../lnurl/payment/lnurl_payment_handler.dart | 18 +-- .../lnurl/payment/lnurl_payment_page.dart | 6 +- .../lnurl/withdraw/lnurl_withdraw_dialog.dart | 22 ++-- .../withdraw/lnurl_withdraw_handler.dart | 10 +- lib/routes/lsp/widgets/lsp_list_widget.dart | 6 +- .../widget/mempool_settings_widget.dart | 6 +- .../payment_options/widget/actions_fee.dart | 8 +- .../widget/exempt_fee_widget.dart | 10 +- .../payment_options/widget/override_fee.dart | 6 +- .../widget/proportional_fee_widget.dart | 10 +- .../payment_options/widget/save_dialog.dart | 6 +- lib/routes/qr_scan/widgets/qr_scan.dart | 24 ++-- lib/routes/security/secured_page.dart | 14 +-- .../widgets/refund_item_action.dart | 6 +- .../get_refund/widgets/send_onchain_form.dart | 6 +- .../reverse_swap/reverse_swap_page.dart | 6 +- lib/routes/withdraw/sweep/sweep_page.dart | 6 +- .../bitcoin_address_text_form_field.dart | 16 +-- ...withdraw_funds_amount_text_form_field.dart | 8 +- .../widgets/withdraw_funds_available_btc.dart | 6 +- lib/services/deep_links.dart | 6 +- lib/services/device.dart | 18 +-- lib/services/lightning_links.dart | 6 +- lib/services/notifications.dart | 14 +-- lib/user_app.dart | 8 +- lib/utils/exceptions.dart | 10 +- lib/utils/external_browser.dart | 6 +- lib/utils/payment_validator.dart | 16 +-- lib/utils/preferences.dart | 12 +- pubspec.lock | 20 +-- pubspec.yaml | 3 +- test/unit_logger.dart | 26 ++-- 73 files changed, 491 insertions(+), 528 deletions(-) diff --git a/lib/app_config.dart b/lib/app_config.dart index 998f09d7b..722c0bc64 100644 --- a/lib/app_config.dart +++ b/lib/app_config.dart @@ -1,9 +1,9 @@ import 'dart:convert'; import 'package:breez_sdk/bridge_generated.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; -final _log = FimberLog("AppConfig"); +final _log = Logger("AppConfig"); class AppConfig { final String apiKey = const String.fromEnvironment("API_KEY"); @@ -17,7 +17,7 @@ class AppConfig { deviceKey: base64.decode(glKey), ); } catch (e) { - _log.w("Failed to parse partner credentials: $e"); + _log.warning("Failed to parse partner credentials: $e"); return null; } } diff --git a/lib/background/background_task_handler.dart b/lib/background/background_task_handler.dart index a541dec87..03d911d8e 100644 --- a/lib/background/background_task_handler.dart +++ b/lib/background/background_task_handler.dart @@ -1,10 +1,10 @@ import 'dart:io'; import 'package:c_breez/background/payment_hash_poller.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:workmanager/workmanager.dart'; -final log = FimberLog("BackgroundTaskManager"); +final _log = Logger("BackgroundTaskManager"); @pragma('vm:entry-point') // Mandatory if the App is obfuscated or using Flutter 3.1+ class BackgroundTaskManager { @@ -12,7 +12,7 @@ class BackgroundTaskManager { handleBackgroundTask() { Workmanager().executeTask((String taskName, Map? inputData) async { - log.i("Executing task: $taskName\nInput data: ${inputData.toString()}"); + _log.info("Executing task: $taskName\nInput data: ${inputData.toString()}"); if (inputData != null) { switch (inputData["notification_type"]) { case "payment_received": diff --git a/lib/background/breez_message_handler.dart b/lib/background/breez_message_handler.dart index 94f8286fa..83fa9f9af 100644 --- a/lib/background/breez_message_handler.dart +++ b/lib/background/breez_message_handler.dart @@ -2,11 +2,11 @@ import 'dart:io'; import 'package:c_breez/background/breez_service_initializer.dart'; import 'package:c_breez/main.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:workmanager/workmanager.dart'; -final log = FimberLog("BreezMessageHandler"); +final _log = Logger("BreezMessageHandler"); @pragma('vm:entry-point') // Mandatory if the App is obfuscated or using Flutter 3.1+ class BreezMessageHandler { @@ -15,7 +15,7 @@ class BreezMessageHandler { BreezMessageHandler(this.message); Future handleBackgroundMessage() async { - log.i("Handling a background message: ${message.messageId}\nMessage data: ${message.data}"); + _log.info("Handling a background message: ${message.messageId}\nMessage data: ${message.data}"); await initializeBreezServices(); await Workmanager().initialize(callbackDispatcher, isInDebugMode: true); diff --git a/lib/bloc/account/account_bloc.dart b/lib/bloc/account/account_bloc.dart index 69019c193..c26a9e5fc 100644 --- a/lib/bloc/account/account_bloc.dart +++ b/lib/bloc/account/account_bloc.dart @@ -11,7 +11,7 @@ import 'package:c_breez/bloc/account/payment_filters.dart'; import 'package:c_breez/bloc/account/payment_result.dart'; import 'package:c_breez/config.dart'; import 'package:connectivity_plus/connectivity_plus.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter_fgbg/flutter_fgbg.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:path/path.dart' as p; @@ -27,7 +27,7 @@ const nodeSyncInterval = 60; // 1. Synchronizing with the node state. // 2. Abstracting actions exposed by the lightning service. class AccountBloc extends Cubit with HydratedMixin { - final _log = FimberLog("AccountBloc"); + final _log = Logger("AccountBloc"); static const String paymentFilterSettingsKey = "payment_filter_settings"; static const int defaultInvoiceExpiry = Duration.secondsPerHour; @@ -82,7 +82,7 @@ class AccountBloc extends Cubit with HydratedMixin { } Future _startSdkForever() async { - _log.v("starting sdk forever"); + _log.fine("starting sdk forever"); await _startSdkOnce(); // in case we failed to start (lack of inet connection probably) @@ -104,7 +104,7 @@ class AccountBloc extends Cubit with HydratedMixin { } Future _startSdkOnce() async { - _log.v("starting sdk once"); + _log.fine("starting sdk once"); try { emit(state.copyWith(connectionStatus: ConnectionStatus.CONNECTING)); final mnemonic = await _credentialsManager.restoreMnemonic(); @@ -118,7 +118,7 @@ class AccountBloc extends Cubit with HydratedMixin { // Once connected sync sdk periodically on foreground events. void _onConnected() { - _log.v("on connected"); + _log.fine("on connected"); var lastSync = DateTime.fromMillisecondsSinceEpoch(0); FGBGEvents.stream.listen((event) async { if (event == FGBGType.foreground && DateTime.now().difference(lastSync).inSeconds > nodeSyncInterval) { @@ -133,7 +133,7 @@ class AccountBloc extends Cubit with HydratedMixin { required sdk.LnUrlWithdrawRequestData reqData, String? description, }) async { - _log.v("lnurlWithdraw amount: $amountSats, description: '$description', reqData: $reqData"); + _log.fine("lnurlWithdraw amount: $amountSats, description: '$description', reqData: $reqData"); try { return await _breezLib.lnurlWithdraw( amountSats: amountSats, @@ -141,7 +141,7 @@ class AccountBloc extends Cubit with HydratedMixin { description: description, ); } catch (e) { - _log.e("lnurlWithdraw error", ex: e); + _log.severe("lnurlWithdraw error", e); rethrow; } } @@ -151,7 +151,7 @@ class AccountBloc extends Cubit with HydratedMixin { required sdk.LnUrlPayRequestData reqData, String? comment, }) async { - _log.v("lnurlPay amount: $amount, comment: '$comment', reqData: $reqData"); + _log.fine("lnurlPay amount: $amount, comment: '$comment', reqData: $reqData"); try { return await _breezLib.lnurlPay( userAmountSat: amount, @@ -159,7 +159,7 @@ class AccountBloc extends Cubit with HydratedMixin { comment: comment, ); } catch (e) { - _log.e("lnurlPay error", ex: e); + _log.severe("lnurlPay error", e); rethrow; } } @@ -167,27 +167,27 @@ class AccountBloc extends Cubit with HydratedMixin { Future lnurlAuth({ required sdk.LnUrlAuthRequestData reqData, }) async { - _log.v("lnurlAuth amount: reqData: $reqData"); + _log.fine("lnurlAuth amount: reqData: $reqData"); try { return await _breezLib.lnurlAuth(reqData: reqData); } catch (e) { - _log.e("lnurlAuth error", ex: e); + _log.severe("lnurlAuth error", e); rethrow; } } Future sendPayment(String bolt11, int? amountSats) async { - _log.v("sendPayment: $bolt11, $amountSats"); + _log.fine("sendPayment: $bolt11, $amountSats"); try { await _breezLib.sendPayment(bolt11: bolt11, amountSats: amountSats); } catch (e) { - _log.e("sendPayment error", ex: e); + _log.severe("sendPayment error", e); return Future.error(e); } } Future cancelPayment(String bolt11) async { - _log.v("cancelPayment: $bolt11"); + _log.fine("cancelPayment: $bolt11"); throw Exception("not implemented"); } @@ -196,21 +196,21 @@ class AccountBloc extends Cubit with HydratedMixin { String description, int amountSats, ) async { - _log.v("sendSpontaneousPayment: $nodeId, $description, $amountSats"); - _log.i("description field is not being used by the SDK yet"); + _log.fine("sendSpontaneousPayment: $nodeId, $description, $amountSats"); + _log.info("description field is not being used by the SDK yet"); try { await _breezLib.sendSpontaneousPayment( nodeId: nodeId, amountSats: amountSats, ); } catch (e) { - _log.e("sendSpontaneousPayment error", ex: e); + _log.severe("sendSpontaneousPayment error", e); return Future.error(e); } } Future isValidBitcoinAddress(String? address) async { - _log.v("isValidBitcoinAddress: $address"); + _log.fine("isValidBitcoinAddress: $address"); if (address == null) return false; return _breezLib.isValidBitcoinAddress(address); } @@ -223,10 +223,10 @@ class AccountBloc extends Cubit with HydratedMixin { bool channelCreationPossible, { int? channelMinimumFee, }) { - _log.v("validatePayment: $amount, $outgoing, $channelMinimumFee"); + _log.fine("validatePayment: $amount, $outgoing, $channelMinimumFee"); var accState = state; if (amount > accState.maxPaymentAmount) { - _log.v("Amount $amount is bigger than maxPaymentAmount ${accState.maxPaymentAmount}"); + _log.fine("Amount $amount is bigger than maxPaymentAmount ${accState.maxPaymentAmount}"); throw PaymentExceededLimitError(accState.maxPaymentAmount); } @@ -246,9 +246,9 @@ class AccountBloc extends Cubit with HydratedMixin { } if (outgoing && amount > accState.maxAllowedToPay) { - _log.v("Outgoing but amount $amount is bigger than ${accState.maxAllowedToPay}"); + _log.fine("Outgoing but amount $amount is bigger than ${accState.maxAllowedToPay}"); if (accState.reserveAmount > 0) { - _log.v("Reserve amount ${accState.reserveAmount}"); + _log.fine("Reserve amount ${accState.reserveAmount}"); throw PaymentBelowReserveError(accState.reserveAmount); } throw const InsufficientLocalBalanceError(); @@ -260,7 +260,7 @@ class AccountBloc extends Cubit with HydratedMixin { int? fromTimestamp, int? toTimestamp, }) async { - _log.v("changePaymentFilter: $filter, $fromTimestamp, $toTimestamp"); + _log.fine("changePaymentFilter: $filter, $fromTimestamp, $toTimestamp"); _paymentFiltersStreamController.add( state.paymentFilters.copyWith( filter: filter, @@ -274,7 +274,7 @@ class AccountBloc extends Cubit with HydratedMixin { String description = "", required int amountSats, }) async { - _log.v("addInvoice: $description, $amountSats"); + _log.fine("addInvoice: $description, $amountSats"); final requestData = sdk.ReceivePaymentRequest(amountSats: amountSats, description: description); final responseData = await _breezLib.receivePayment(reqData: requestData); @@ -292,12 +292,12 @@ class AccountBloc extends Cubit with HydratedMixin { } Future> exportCredentialFiles() async { - _log.v("exportCredentialFiles"); + _log.fine("exportCredentialFiles"); return _credentialsManager.exportCredentials(); } void recursiveFolderCopySync(String path1, String path2) { - _log.v("recursiveFolderCopySync: $path1, $path2"); + _log.fine("recursiveFolderCopySync: $path1, $path2"); Directory dir1 = Directory(path1); Directory dir2 = Directory(path2); if (!dir2.existsSync()) { @@ -317,7 +317,7 @@ class AccountBloc extends Cubit with HydratedMixin { } void _listenPaymentResultEvents() { - _log.v("_listenPaymentResultEvents"); + _log.fine("_listenPaymentResultEvents"); _breezLib.paymentResultStream.listen((paymentInfo) { _paymentResultStreamController.add( PaymentResult(paymentInfo: paymentInfo), @@ -328,7 +328,7 @@ class AccountBloc extends Cubit with HydratedMixin { } void mnemonicsValidated() { - _log.v("mnemonicsValidated"); + _log.fine("mnemonicsValidated"); emit(state.copyWith(verificationStatus: VerificationStatus.VERIFIED)); } } diff --git a/lib/bloc/account/credentials_manager.dart b/lib/bloc/account/credentials_manager.dart index 90233e309..d9dc35a2b 100644 --- a/lib/bloc/account/credentials_manager.dart +++ b/lib/bloc/account/credentials_manager.dart @@ -1,11 +1,11 @@ import 'dart:io'; import 'package:c_breez/services/keychain.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:path_provider/path_provider.dart'; class CredentialsManager { - final _log = FimberLog("CredentialsManager"); + final _log = Logger("CredentialsManager"); static const String accountMnemonic = "account_mnemonic"; final KeyChain keyChain; @@ -17,7 +17,7 @@ class CredentialsManager { }) async { try { await _storeMnemonic(mnemonic); - _log.i("Stored credentials successfully"); + _log.info("Stored credentials successfully"); } catch (err) { throw Exception(err.toString()); } @@ -26,7 +26,7 @@ class CredentialsManager { Future restoreMnemonic() async { try { String? mnemonicStr = await keyChain.read(accountMnemonic); - _log.i("Restored credentials successfully"); + _log.info("Restored credentials successfully"); return mnemonicStr!; } catch (err) { throw Exception(err.toString()); diff --git a/lib/bloc/backup/backup_bloc.dart b/lib/bloc/backup/backup_bloc.dart index 76c00acc1..16ed10744 100644 --- a/lib/bloc/backup/backup_bloc.dart +++ b/lib/bloc/backup/backup_bloc.dart @@ -1,11 +1,11 @@ import 'package:breez_sdk/breez_sdk.dart'; import 'package:breez_sdk/bridge_generated.dart' as sdk; import 'package:c_breez/bloc/backup/backup_state.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; class BackupBloc extends Cubit { - final _log = FimberLog("BackupBloc"); + final _log = Logger("BackupBloc"); final BreezSDK _breezLib; BackupBloc(this._breezLib) : super(null) { @@ -13,18 +13,18 @@ class BackupBloc extends Cubit { } _listenBackupEvents() { - _log.v("_listenBackupEvents"); + _log.fine("_listenBackupEvents"); _breezLib.backupStream.listen((event) { - _log.i('got state: $event'); + _log.info('got state: $event'); if (event is sdk.BreezEvent_BackupStarted) { emit(BackupState(status: BackupStatus.INPROGRESS)); } if (event is sdk.BreezEvent_BackupSucceeded) { - _log.i("BreezEvent_BackupSucceeded, backupbloc"); + _log.info("BreezEvent_BackupSucceeded, backupbloc"); emit(BackupState(status: BackupStatus.SUCCESS)); } if (event is sdk.BreezEvent_BackupFailed) { - _log.i("BreezEvent_BackupFailed"); + _log.info("BreezEvent_BackupFailed"); emit(BackupState(status: BackupStatus.FAILED)); } }, onError: (error) { diff --git a/lib/bloc/buy_bitcoin/moonpay/moonpay_bloc.dart b/lib/bloc/buy_bitcoin/moonpay/moonpay_bloc.dart index 02e1dfdcc..4c6c0ac89 100644 --- a/lib/bloc/buy_bitcoin/moonpay/moonpay_bloc.dart +++ b/lib/bloc/buy_bitcoin/moonpay/moonpay_bloc.dart @@ -5,10 +5,10 @@ import 'package:c_breez/bloc/buy_bitcoin/moonpay/moonpay_state.dart'; import 'package:c_breez/config.dart'; import 'package:c_breez/utils/exceptions.dart'; import 'package:c_breez/utils/preferences.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("MoonPayBloc"); +final _log = Logger("MoonPayBloc"); class MoonPayBloc extends Cubit { final BreezSDK _breezLib; @@ -21,12 +21,12 @@ class MoonPayBloc extends Cubit { Future fetchMoonpayUrl() async { try { - _log.v("fetchMoonpayUrl"); + _log.fine("fetchMoonpayUrl"); emit(MoonPayState.loading()); final swapInProgress = (await _breezLib.inProgressSwap()); if (swapInProgress != null) { - _log.v("fetchMoonpayUrl swapInfo: $swapInProgress"); + _log.fine("fetchMoonpayUrl swapInfo: $swapInProgress"); emit(MoonPayState.swapInProgress( swapInProgress.bitcoinAddress, swapInProgress.status == sdk.SwapStatus.Expired)); return; @@ -34,7 +34,7 @@ class MoonPayBloc extends Cubit { sdk.BuyBitcoinRequest reqData = const sdk.BuyBitcoinRequest(provider: sdk.BuyBitcoinProvider.Moonpay); final buyBitcoinResponse = await _breezLib.buyBitcoin(reqData: reqData); - _log.v("fetchMoonpayUrl url: ${buyBitcoinResponse.url}"); + _log.fine("fetchMoonpayUrl url: ${buyBitcoinResponse.url}"); if (buyBitcoinResponse.openingFeeParams != null) { emit(MoonPayState.urlReady(buyBitcoinResponse)); return; @@ -42,31 +42,31 @@ class MoonPayBloc extends Cubit { emit(MoonPayState.error(getSystemAppLocalizations().add_funds_moonpay_error_address)); } catch (e) { - _log.e("fetchMoonpayUrl error: $e"); + _log.severe("fetchMoonpayUrl error: $e"); emit(MoonPayState.error(extractExceptionMessage(e, getSystemAppLocalizations()))); } } void updateWebViewStatus(WebViewStatus status) { - _log.v("updateWebViewStatus status: $status"); + _log.fine("updateWebViewStatus status: $status"); final state = this.state; if (state is MoonPayStateUrlReady) { emit(state.copyWith(webViewStatus: status)); } else { - _log.e("updateWebViewStatus state is not MoonPayStateUrlReady"); + _log.severe("updateWebViewStatus state is not MoonPayStateUrlReady"); } } Future makeExplorerUrl(String address) async { - _log.v("openExplorer address: $address"); + _log.fine("openExplorer address: $address"); final mempoolUrl = await _preferences.getMempoolSpaceUrl() ?? (await Config.instance()).defaultMempoolUrl; final url = "$mempoolUrl/address/$address"; - _log.v("openExplorer url: $url"); + _log.fine("openExplorer url: $url"); return url; } void dispose() { - _log.v("dispose"); + _log.fine("dispose"); emit(MoonPayState.initial()); } } diff --git a/lib/bloc/connectivity/connectivity_bloc.dart b/lib/bloc/connectivity/connectivity_bloc.dart index 479bd95de..cc0e5d1fc 100644 --- a/lib/bloc/connectivity/connectivity_bloc.dart +++ b/lib/bloc/connectivity/connectivity_bloc.dart @@ -2,14 +2,14 @@ import 'dart:async'; import 'dart:io'; import 'package:connectivity_plus/connectivity_plus.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'connectivity_state.dart'; class ConnectivityBloc extends Cubit { - final _log = FimberLog("ConnectivityBloc"); + final _log = Logger("ConnectivityBloc"); final Connectivity _connectivity = Connectivity(); @@ -28,7 +28,7 @@ class ConnectivityBloc extends Cubit { try { result = await _updateConnectionStatus(await _connectivity.checkConnectivity()); } on PlatformException catch (e) { - _log.e("Failed to check connectivity", ex: e); + _log.severe("Failed to check connectivity", e); rethrow; } final connectivityState = ConnectivityState(lastStatus: result); @@ -37,7 +37,7 @@ class ConnectivityBloc extends Cubit { } Future _updateConnectionStatus(ConnectivityResult connectionStatus) async { - _log.i("Connection status changed to: ${connectionStatus.name}"); + _log.info("Connection status changed to: ${connectionStatus.name}"); if (connectionStatus != ConnectivityResult.none) { bool isDeviceConnected = await _isConnected(); if (!isDeviceConnected) { @@ -55,11 +55,11 @@ class ConnectivityBloc extends Cubit { if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) { return true; } else { - _log.e("Connection has no internet access"); + _log.severe("Connection has no internet access"); return false; } } on SocketException catch (e) { - _log.e("Socket operation failed", ex: e); + _log.severe("Socket operation failed", e); return false; } } diff --git a/lib/bloc/csv_exporter.dart b/lib/bloc/csv_exporter.dart index d9dc47424..50c07d66c 100644 --- a/lib/bloc/csv_exporter.dart +++ b/lib/bloc/csv_exporter.dart @@ -7,11 +7,11 @@ import 'package:c_breez/bloc/account/payment_filters.dart'; import 'package:c_breez/models/payment_minutiae.dart'; import 'package:c_breez/utils/date.dart'; import 'package:csv/csv.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:intl/intl.dart'; import 'package:path_provider/path_provider.dart'; -final _log = FimberLog("CsvExporter"); +final _log = Logger("CsvExporter"); class CsvExporter { final AccountState accountState; @@ -31,16 +31,16 @@ class CsvExporter { }); Future export() async { - _log.i("export payments started"); + _log.info("export payments started"); String tmpFilePath = await _saveCsvFile(const ListToCsvConverter().convert(_generateList() as List)); - _log.i("export payments finished"); + _log.info("export payments finished"); return tmpFilePath; } List _generateList() { // fetch currencystate map values accordingly - _log.i("generating payment list started"); + _log.info("generating payment list started"); final texts = getSystemAppLocalizations(); final data = _filterPaymentData(accountState.payments, accountState.paymentFilters); @@ -72,7 +72,7 @@ class CsvExporter { texts.csv_exporter_tx_hash, texts.csv_exporter_fee, ]); - _log.i("generating payment finished"); + _log.info("generating payment finished"); return paymentList; } @@ -94,26 +94,26 @@ class CsvExporter { } Future _saveCsvFile(String csv) async { - _log.i("save breez payments to csv started"); + _log.info("save breez payments to csv started"); String filePath = await _createCsvFilePath(); final file = File(filePath); await file.writeAsString(csv); - _log.i("save breez payments to csv finished"); + _log.info("save breez payments to csv finished"); return file.path; } Future _createCsvFilePath() async { - _log.i("create breez payments path started"); + _log.info("create breez payments path started"); final directory = await getTemporaryDirectory(); String filePath = '${directory.path}/BreezPayments'; filePath = _appendFilterInformation(filePath); filePath += ".csv"; - _log.i("create breez payments path finished"); + _log.info("create breez payments path finished"); return filePath; } String _appendFilterInformation(String filePath) { - _log.i("add filter information to path started"); + _log.info("add filter information to path started"); if (filter == PaymentTypeFilter.Sent) { filePath += "_sent"; } else if (filter == PaymentTypeFilter.Received) { @@ -124,7 +124,7 @@ class CsvExporter { String dateFilter = '${dateFilterFormat.format(startDate!)}-${dateFilterFormat.format(endDate!)}'; filePath += "_$dateFilter"; } - _log.i("add filter information to path finished"); + _log.info("add filter information to path finished"); return filePath; } } diff --git a/lib/bloc/fee_options/fee_options_bloc.dart b/lib/bloc/fee_options/fee_options_bloc.dart index 9da9ac30f..41835c861 100644 --- a/lib/bloc/fee_options/fee_options_bloc.dart +++ b/lib/bloc/fee_options/fee_options_bloc.dart @@ -6,10 +6,10 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/fee_options/fee_option.dart'; import 'package:c_breez/bloc/fee_options/fee_options_state.dart'; import 'package:c_breez/utils/exceptions.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; -final _log = FimberLog("FeeOptionsBloc"); +final _log = Logger("FeeOptionsBloc"); class FeeOptionsBloc extends Cubit { final BreezSDK _breezLib; @@ -19,14 +19,14 @@ class FeeOptionsBloc extends Cubit { /// Lookup the most recent reverse swap pair info using the Boltz API Future fetchReverseSwapFees({int? sendAmountSat}) async { try { - _log.v("Estimate reverse swap fees for: $sendAmountSat"); + _log.fine("Estimate reverse swap fees for: $sendAmountSat"); final req = ReverseSwapFeesRequest(sendAmountSat: sendAmountSat); ReverseSwapPairInfo reverseSwapPairInfo = await _breezLib.fetchReverseSwapFees(req: req); - _log.v("Total estimated fees for reverse swap: ${reverseSwapPairInfo.totalEstimatedFees}"); + _log.fine("Total estimated fees for reverse swap: ${reverseSwapPairInfo.totalEstimatedFees}"); emit(state.copyWith(reverseSwapPairInfo: reverseSwapPairInfo, error: "")); return reverseSwapPairInfo; } catch (e) { - _log.e("fetchReverseSwapFees error", ex: e); + _log.severe("fetchReverseSwapFees error", e); emit(FeeOptionsState(error: extractExceptionMessage(e, getSystemAppLocalizations()))); rethrow; } @@ -37,14 +37,14 @@ class FeeOptionsBloc extends Cubit { RecommendedFees recommendedFees; try { recommendedFees = await _breezLib.recommendedFees(); - _log.v( + _log.fine( "fetchFeeOptions recommendedFees:\nfastestFee: ${recommendedFees.fastestFee}," "\nhalfHourFee: ${recommendedFees.halfHourFee},\nhourFee: ${recommendedFees.hourFee}.", ); final utxos = await _retrieveUTXOS(); return _constructFeeOptionList(utxos, recommendedFees); } catch (e) { - _log.e("fetchFeeOptions error", ex: e); + _log.severe("fetchFeeOptions error", e); emit(FeeOptionsState(error: extractExceptionMessage(e, getSystemAppLocalizations()))); rethrow; } @@ -53,11 +53,11 @@ class FeeOptionsBloc extends Cubit { Future _retrieveUTXOS() async { final nodeState = await _breezLib.nodeInfo(); if (nodeState == null) { - _log.e("_retrieveUTXOS Failed to get node state"); + _log.severe("_retrieveUTXOS Failed to get node state"); throw Exception(getSystemAppLocalizations().node_state_error); } final utxos = nodeState.utxos.length; - _log.v("_retrieveUTXOS utxos: $utxos"); + _log.fine("_retrieveUTXOS utxos: $utxos"); return utxos; } diff --git a/lib/bloc/input/input_bloc.dart b/lib/bloc/input/input_bloc.dart index 616e6701a..279b0493f 100644 --- a/lib/bloc/input/input_bloc.dart +++ b/lib/bloc/input/input_bloc.dart @@ -6,12 +6,12 @@ import 'package:c_breez/bloc/input/input_state.dart'; import 'package:c_breez/models/invoice.dart'; import 'package:c_breez/services/device.dart'; import 'package:c_breez/services/lightning_links.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:rxdart/rxdart.dart'; class InputBloc extends Cubit { - final _log = FimberLog("InputBloc"); + final _log = Logger("InputBloc"); final BreezSDK _breezLib; final LightningLinksService _lightningLinks; final Device _device; @@ -27,19 +27,19 @@ class InputBloc extends Cubit { } void _initializeInputBloc() async { - _log.d("initializeInputBloc"); + _log.config("initializeInputBloc"); await _breezLib.nodeStateStream.firstWhere((nodeState) => nodeState != null); _watchIncomingInvoices().listen((inputState) => emit(inputState!)); } void addIncomingInput(String bolt11) { - _log.v("addIncomingInput: $bolt11"); + _log.fine("addIncomingInput: $bolt11"); _decodeInvoiceController.add(bolt11); } Future trackPayment(String paymentHash) async { await _breezLib.invoicePaidStream.firstWhere((invoice) { - _log.v("invoice paid: ${invoice.paymentHash} we are waiting for " + _log.fine("invoice paid: ${invoice.paymentHash} we are waiting for " "$paymentHash, same: ${invoice.paymentHash == paymentHash}"); return invoice.paymentHash == paymentHash; }); @@ -47,11 +47,11 @@ class InputBloc extends Cubit { Stream _watchIncomingInvoices() { return Rx.merge([ - _decodeInvoiceController.stream.doOnData((event) => _log.v("decodeInvoiceController: $event")), - _lightningLinks.linksNotifications.doOnData((event) => _log.v("lightningLinks: $event")), - _device.clipboardStream.distinct().skip(1).doOnData((event) => _log.v("clipboardStream: $event")), + _decodeInvoiceController.stream.doOnData((event) => _log.fine("decodeInvoiceController: $event")), + _lightningLinks.linksNotifications.doOnData((event) => _log.fine("lightningLinks: $event")), + _device.clipboardStream.distinct().skip(1).doOnData((event) => _log.fine("clipboardStream: $event")), ]).asyncMap((input) async { - _log.v("Incoming input: '$input'"); + _log.fine("Incoming input: '$input'"); // Emit an empty InputState with isLoading to display a loader on UI layer emit(InputState(isLoading: true)); try { @@ -60,7 +60,7 @@ class InputBloc extends Cubit { _logParsedInput(parsedInput); return await _handleParsedInput(parsedInput); } catch (e) { - _log.e("Failed to parse input", ex: e); + _log.severe("Failed to parse input", e); return InputState(isLoading: false); } }); @@ -100,10 +100,10 @@ class InputBloc extends Cubit { void _logParsedInput(InputType parsedInput) { // Todo: Find a better way to serialize parsed input - _log.v("Parsed input type: '${parsedInput.runtimeType.toString()}"); + _log.fine("Parsed input type: '${parsedInput.runtimeType.toString()}"); if (parsedInput is InputType_Bolt11) { final lnInvoice = parsedInput.invoice; - _log.i( + _log.info( "bolt11: ${lnInvoice.bolt11}\n" "payeePubkey: ${lnInvoice.payeePubkey}\n" "paymentHash: ${lnInvoice.paymentHash}\n" @@ -117,7 +117,7 @@ class InputBloc extends Cubit { ); } else if (parsedInput is InputType_LnUrlPay) { final lnUrlPayReqData = parsedInput.data; - _log.i( + _log.info( "${lnUrlPayReqData.toString()}\n" "callback: ${lnUrlPayReqData.callback}\n" "minSendable: ${lnUrlPayReqData.minSendable}\n" @@ -128,7 +128,7 @@ class InputBloc extends Cubit { ); } else if (parsedInput is InputType_LnUrlWithdraw) { final lnUrlWithdrawReqData = parsedInput.data; - _log.i( + _log.info( "callback: ${lnUrlWithdrawReqData.callback}\n" "k1: ${lnUrlWithdrawReqData.k1}\n" "defaultDescription: ${lnUrlWithdrawReqData.defaultDescription}\n" @@ -137,14 +137,14 @@ class InputBloc extends Cubit { ); } else if (parsedInput is InputType_LnUrlAuth) { final lnUrlAuthReqData = parsedInput.data; - _log.i("k1: ${lnUrlAuthReqData.k1}"); + _log.info("k1: ${lnUrlAuthReqData.k1}"); } else if (parsedInput is InputType_LnUrlError) { final lnUrlErrorData = parsedInput.data; - _log.i("reason: ${lnUrlErrorData.reason}"); + _log.info("reason: ${lnUrlErrorData.reason}"); } else if (parsedInput is InputType_NodeId) { - _log.i("nodeId: ${parsedInput.nodeId}"); + _log.info("nodeId: ${parsedInput.nodeId}"); } else if (parsedInput is InputType_Url) { - _log.i("url: ${parsedInput.url}"); + _log.info("url: ${parsedInput.url}"); } } diff --git a/lib/bloc/network/network_settings_bloc.dart b/lib/bloc/network/network_settings_bloc.dart index 65552840b..2f46b1a4b 100644 --- a/lib/bloc/network/network_settings_bloc.dart +++ b/lib/bloc/network/network_settings_bloc.dart @@ -1,7 +1,7 @@ import 'package:c_breez/bloc/network/network_settings_state.dart'; import 'package:c_breez/config.dart' as lib; import 'package:c_breez/utils/preferences.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:http/http.dart' as http; import 'package:hydrated_bloc/hydrated_bloc.dart'; @@ -9,7 +9,7 @@ class NetworkSettingsBloc extends Cubit with HydratedMixin final Preferences _preferences; final http.Client _httpClient; final lib.Config _config; - final _log = FimberLog("NetworkSettingsBloc"); + final _log = Logger("NetworkSettingsBloc"); NetworkSettingsBloc( this._preferences, @@ -17,38 +17,38 @@ class NetworkSettingsBloc extends Cubit with HydratedMixin http.Client? httpClient, }) : _httpClient = httpClient ?? http.Client(), super(NetworkSettingsState.initial()) { - _fetchMempoolSettings().then((_) => _log.v("Initial mempool settings read")); + _fetchMempoolSettings().then((_) => _log.fine("Initial mempool settings read")); } Future setMempoolUrl(String mempoolUrl) async { - _log.v("Changing mempool url to: $mempoolUrl"); + _log.fine("Changing mempool url to: $mempoolUrl"); Uri? uri; try { if (mempoolUrl.startsWith(RegExp(r'\d'))) { - _log.v("Mempool url starts with a digit, adding https://"); + _log.fine("Mempool url starts with a digit, adding https://"); uri = Uri.parse("https://$mempoolUrl"); } else { uri = Uri.parse(mempoolUrl); } } catch (e) { - _log.w("Invalid mempool url: $mempoolUrl"); + _log.warning("Invalid mempool url: $mempoolUrl"); return false; } if (!uri.hasScheme) { - _log.v("Mempool url scheme is missing, adding https://"); + _log.fine("Mempool url scheme is missing, adding https://"); try { uri = Uri.parse("https://$mempoolUrl"); } catch (e) { - _log.w("Invalid mempool url: $mempoolUrl"); + _log.warning("Invalid mempool url: $mempoolUrl"); return false; } } if (!uri.hasScheme || !uri.hasAuthority) { - _log.w("Invalid mempool url: $mempoolUrl"); + _log.warning("Invalid mempool url: $mempoolUrl"); return false; } if (!await _testUri(uri)) { - _log.w("Mempool url is not reachable: $mempoolUrl"); + _log.warning("Mempool url is not reachable: $mempoolUrl"); return false; } final port = uri.hasPort ? ":${uri.port}" : ""; @@ -58,7 +58,7 @@ class NetworkSettingsBloc extends Cubit with HydratedMixin } Future resetMempoolSpaceSettings() async { - _log.v("Resetting mempool url to default"); + _log.fine("Resetting mempool url to default"); await _preferences.resetMempoolSpaceUrl(); await _fetchMempoolSettings(); } @@ -74,10 +74,10 @@ class NetworkSettingsBloc extends Cubit with HydratedMixin } Future _fetchMempoolSettings() async { - _log.v("Fetching mempool settings"); + _log.fine("Fetching mempool settings"); final mempoolUrl = await _preferences.getMempoolSpaceUrl(); final mempoolDefaultUrl = _config.defaultMempoolUrl; - _log.v("Mempool url fetched: $mempoolUrl, default: $mempoolDefaultUrl"); + _log.fine("Mempool url fetched: $mempoolUrl, default: $mempoolDefaultUrl"); emit(state.copyWith( mempoolUrl: mempoolUrl ?? mempoolDefaultUrl, )); @@ -88,7 +88,7 @@ class NetworkSettingsBloc extends Cubit with HydratedMixin final response = await _httpClient.get(uri); return response.statusCode < 400; } catch (e) { - _log.w("Failed to test mempool url: $uri", ex: e); + _log.warning("Failed to test mempool url: $uri", e); return false; } } diff --git a/lib/bloc/payment_options/payment_options_bloc.dart b/lib/bloc/payment_options/payment_options_bloc.dart index fa63e6c38..f343801a8 100644 --- a/lib/bloc/payment_options/payment_options_bloc.dart +++ b/lib/bloc/payment_options/payment_options_bloc.dart @@ -1,9 +1,9 @@ import 'package:c_breez/bloc/payment_options/payment_options_state.dart'; import 'package:c_breez/utils/preferences.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; -final _log = FimberLog("PaymentOptionsBloc"); +final _log = Logger("PaymentOptionsBloc"); class PaymentOptionsBloc extends Cubit { final Preferences _preferences; @@ -11,7 +11,7 @@ class PaymentOptionsBloc extends Cubit { PaymentOptionsBloc( this._preferences, ) : super(const PaymentOptionsState.initial()) { - _fetchPaymentsOverrideSettings().then((_) => _log.v("Initial settings read")); + _fetchPaymentsOverrideSettings().then((_) => _log.fine("Initial settings read")); } Future setOverrideFeeEnabled(bool enabled) async { @@ -36,7 +36,7 @@ class PaymentOptionsBloc extends Cubit { } Future resetFees() async { - _log.v("Resetting payments override settings to default: enabled: $kDefaultOverrideFee, " + _log.fine("Resetting payments override settings to default: enabled: $kDefaultOverrideFee, " "proportional: $kDefaultProportionalFee"); await _preferences.setPaymentOptionsOverrideFeeEnabled(kDefaultOverrideFee); await _preferences.setPaymentOptionsProportionalFee(kDefaultProportionalFee); @@ -46,7 +46,7 @@ class PaymentOptionsBloc extends Cubit { Future saveFees() async { final state = this.state; - _log.v("Saving payments override settings: enabled: ${state.overrideFeeEnabled}, " + _log.fine("Saving payments override settings: enabled: ${state.overrideFeeEnabled}, " "proportional: ${state.proportionalFee}" "Exemptfee: ${state.exemptFeeMsat}"); await _preferences.setPaymentOptionsOverrideFeeEnabled(state.overrideFeeEnabled); @@ -56,18 +56,18 @@ class PaymentOptionsBloc extends Cubit { } Future cancelEditing() async { - _log.v("Canceling editing"); + _log.fine("Canceling editing"); if (state.saveEnabled) { await _fetchPaymentsOverrideSettings(); } } Future _fetchPaymentsOverrideSettings() async { - _log.v("Fetching payments override settings"); + _log.fine("Fetching payments override settings"); final enabled = await _preferences.getPaymentOptionsOverrideFeeEnabled(); final proportional = await _preferences.getPaymentOptionsProportionalFee(); final exemptFeeMsat = await _preferences.getPaymentOptionsExemptFee(); - _log.v( + _log.fine( "Payments override fetched: enabled: $enabled, proportional: $proportional, exemptFeeMsat: $exemptFeeMsat"); emit(PaymentOptionsState( overrideFeeEnabled: enabled, diff --git a/lib/bloc/refund/refund_bloc.dart b/lib/bloc/refund/refund_bloc.dart index c19348a07..1ab8b5086 100644 --- a/lib/bloc/refund/refund_bloc.dart +++ b/lib/bloc/refund/refund_bloc.dart @@ -2,10 +2,10 @@ import 'dart:async'; import 'package:breez_sdk/breez_sdk.dart'; import 'package:c_breez/bloc/refund/refund_state.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("RefundBloc"); +final _log = Logger("RefundBloc"); class RefundBloc extends Cubit { final BreezSDK _breezLib; @@ -32,17 +32,17 @@ class RefundBloc extends Cubit { required String toAddress, required int satPerVbyte, }) async { - _log.v("Refunding swap $swapAddress to $toAddress with fee $satPerVbyte"); + _log.fine("Refunding swap $swapAddress to $toAddress with fee $satPerVbyte"); try { final txId = await _breezLib.refund( swapAddress: swapAddress, toAddress: toAddress, satPerVbyte: satPerVbyte, ); - _log.v("Refund txId: $txId"); + _log.fine("Refund txId: $txId"); return txId; } catch (e) { - _log.e("Failed to refund swap", ex: e); + _log.severe("Failed to refund swap", e); rethrow; } } diff --git a/lib/bloc/rev_swap_in_progress/rev_swap_in_progress_bloc.dart b/lib/bloc/rev_swap_in_progress/rev_swap_in_progress_bloc.dart index 9bd6cc076..2d006cbb7 100644 --- a/lib/bloc/rev_swap_in_progress/rev_swap_in_progress_bloc.dart +++ b/lib/bloc/rev_swap_in_progress/rev_swap_in_progress_bloc.dart @@ -4,10 +4,10 @@ import 'package:breez_sdk/breez_sdk.dart'; import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/rev_swap_in_progress/rev_swap_in_progress_state.dart'; import 'package:c_breez/utils/exceptions.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("RevSwapsInProgressBloc"); +final _log = Logger("RevSwapsInProgressBloc"); class RevSwapsInProgressBloc extends Cubit { final BreezSDK _breezLib; @@ -19,7 +19,7 @@ class RevSwapsInProgressBloc extends Cubit { late Timer timer; pollReverseSwapsInProgress() { - _log.i("reverse swaps in progress polling started"); + _log.info("reverse swaps in progress polling started"); emit(RevSwapsInProgressState(isLoading: true)); timer = Timer.periodic(const Duration(seconds: 5), _refreshInProgressReverseSwaps); _refreshInProgressReverseSwaps(timer); @@ -30,7 +30,7 @@ class RevSwapsInProgressBloc extends Cubit { try { final reverseSwapsInProgress = await _breezLib.inProgressReverseSwaps(); for (var revSwapInfo in reverseSwapsInProgress) { - _log.i( + _log.info( "Reverse Swap ${revSwapInfo.id} to ${revSwapInfo.claimPubkey} for ${revSwapInfo.onchainAmountSat} sats status:${revSwapInfo.status.name}", ); } @@ -39,14 +39,14 @@ class RevSwapsInProgressBloc extends Cubit { final errorMessage = extractExceptionMessage(e, texts); emit(RevSwapsInProgressState(error: errorMessage)); timer.cancel(); - _log.i("reverse swaps in progress polling finished due to error"); + _log.info("reverse swaps in progress polling finished due to error"); } } @override Future close() { timer.cancel(); - _log.i("reverse swaps in progress polling finished"); + _log.info("reverse swaps in progress polling finished"); return super.close(); } } diff --git a/lib/bloc/reverse_swap/reverse_swap_bloc.dart b/lib/bloc/reverse_swap/reverse_swap_bloc.dart index b8a2664fc..2d1d151ac 100644 --- a/lib/bloc/reverse_swap/reverse_swap_bloc.dart +++ b/lib/bloc/reverse_swap/reverse_swap_bloc.dart @@ -5,10 +5,10 @@ import 'package:breez_sdk/bridge_generated.dart'; import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/reverse_swap/reverse_swap_state.dart'; import 'package:c_breez/utils/exceptions.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; -final _log = FimberLog("ReverseSwapBloc"); +final _log = Logger("ReverseSwapBloc"); class ReverseSwapBloc extends Cubit { final BreezSDK _breezLib; @@ -22,7 +22,7 @@ class ReverseSwapBloc extends Cubit { required int satPerVbyte, }) async { try { - _log.v( + _log.fine( "Reverse Swap of $amountSat sats to address $onchainRecipientAddress using $satPerVbyte sats/vByte as" " fee rate w/ pairHash: $pairHash", ); @@ -32,14 +32,14 @@ class ReverseSwapBloc extends Cubit { pairHash: pairHash, satPerVbyte: satPerVbyte, ); - _log.v( + _log.fine( "Reverse Swap Info for id: ${reverseSwapInfo.id}, ${reverseSwapInfo.onchainAmountSat} sats to address" " ${reverseSwapInfo.claimPubkey} w/ status: ${reverseSwapInfo.status}", ); emit(ReverseSwapState(reverseSwapInfo: reverseSwapInfo)); return reverseSwapInfo; } catch (e) { - _log.e("sendOnchain error", ex: e); + _log.severe("sendOnchain error", e); emit(ReverseSwapState(error: extractExceptionMessage(e, getSystemAppLocalizations()))); rethrow; } diff --git a/lib/bloc/security/security_bloc.dart b/lib/bloc/security/security_bloc.dart index 452bf198c..14833f8f2 100644 --- a/lib/bloc/security/security_bloc.dart +++ b/lib/bloc/security/security_bloc.dart @@ -2,7 +2,7 @@ import 'dart:async'; import 'dart:io'; import 'package:c_breez/bloc/security/security_state.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/services.dart'; import 'package:flutter_fgbg/flutter_fgbg.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; @@ -12,7 +12,7 @@ import 'package:local_auth_android/local_auth_android.dart'; import 'package:local_auth_ios/types/auth_messages_ios.dart'; class SecurityBloc extends Cubit with HydratedMixin { - final _log = FimberLog("LocalAuthenticationService"); + final _log = Logger("LocalAuthenticationService"); final _auth = LocalAuthentication(); final _secureStorage = const FlutterSecureStorage(); Timer? _autoLock; @@ -110,7 +110,7 @@ class SecurityBloc extends Cubit with HydratedMixin { if (error.code == "LockedOut" || error.code == "PermanentlyLockedOut") { throw error.message!; } - _log.e("Error Code: ${error.code} - Message: ${error.message}", ex: error); + _log.severe("Error Code: ${error.code} - Message: ${error.message}", error); await _auth.stopAuthentication(); _setLockState(LockState.locked); return false; diff --git a/lib/bloc/swap_in_progress/swap_in_progress_bloc.dart b/lib/bloc/swap_in_progress/swap_in_progress_bloc.dart index 801a0ccc1..880847185 100644 --- a/lib/bloc/swap_in_progress/swap_in_progress_bloc.dart +++ b/lib/bloc/swap_in_progress/swap_in_progress_bloc.dart @@ -5,10 +5,10 @@ import 'package:breez_sdk/bridge_generated.dart'; import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/swap_in_progress/swap_in_progress_state.dart'; import 'package:c_breez/utils/exceptions.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("SwapInProgressBloc"); +final _log = Logger("SwapInProgressBloc"); class SwapInProgressBloc extends Cubit { final BreezSDK _breezLib; @@ -20,7 +20,7 @@ class SwapInProgressBloc extends Cubit { late Timer timer; pollSwapAddress() { - _log.i("swap in address polling started"); + _log.info("swap in address polling started"); emit(SwapInProgressState(null, null, isLoading: true)); timer = Timer.periodic(const Duration(seconds: 5), _refreshAddresses); _refreshAddresses(timer); @@ -37,20 +37,20 @@ class SwapInProgressBloc extends Cubit { } else { swapUnused = (await _breezLib.receiveOnchain(reqData: const ReceiveOnchainRequest())); } - _log.i("swapInProgress: $swapInProgress, swapUnused: $swapUnused"); + _log.info("swapInProgress: $swapInProgress, swapUnused: $swapUnused"); emit(SwapInProgressState(swapInProgress, swapUnused)); } catch (e) { final errorMessage = extractExceptionMessage(e, texts); emit(SwapInProgressState(null, null, error: errorMessage)); timer.cancel(); - _log.i("swap in address polling finished due to error"); + _log.info("swap in address polling finished due to error"); } } @override Future close() { timer.cancel(); - _log.i("swap in address polling finished"); + _log.info("swap in address polling finished"); return super.close(); } } diff --git a/lib/bloc/sweep/sweep_bloc.dart b/lib/bloc/sweep/sweep_bloc.dart index 74707241e..b036c8c41 100644 --- a/lib/bloc/sweep/sweep_bloc.dart +++ b/lib/bloc/sweep/sweep_bloc.dart @@ -5,10 +5,10 @@ import 'package:breez_sdk/bridge_generated.dart'; import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/sweep/sweep_state.dart'; import 'package:c_breez/utils/exceptions.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; -final _log = FimberLog("SweepBloc"); +final _log = Logger("SweepBloc"); class SweepBloc extends Cubit { final BreezSDK _breezLib; @@ -20,13 +20,13 @@ class SweepBloc extends Cubit { required int feeRateSatsPerVbyte, }) async { try { - _log.v("Sweep to address $toAddress using $feeRateSatsPerVbyte fee vByte"); + _log.fine("Sweep to address $toAddress using $feeRateSatsPerVbyte fee vByte"); final request = SweepRequest(toAddress: toAddress, feeRateSatsPerVbyte: feeRateSatsPerVbyte); final sweepRes = await _breezLib.sweep(request: request); emit(SweepState(sweepTxId: sweepRes.txid)); return sweepRes; } catch (e) { - _log.e("sweep error", ex: e); + _log.severe("sweep error", e); emit(SweepState(error: extractExceptionMessage(e, getSystemAppLocalizations()))); rethrow; } diff --git a/lib/bloc/user_profile/user_profile_bloc.dart b/lib/bloc/user_profile/user_profile_bloc.dart index 705e34a9c..8637af508 100644 --- a/lib/bloc/user_profile/user_profile_bloc.dart +++ b/lib/bloc/user_profile/user_profile_bloc.dart @@ -7,13 +7,13 @@ import 'package:c_breez/bloc/user_profile/user_profile_state.dart'; import 'package:c_breez/models/user_profile.dart'; import 'package:c_breez/services/breez_server.dart'; import 'package:c_breez/services/notifications.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:path_provider/path_provider.dart'; const PROFILE_DATA_FOLDER_PATH = "profile"; -final _log = FimberLog("UserProfileBloc"); +final _log = Logger("UserProfileBloc"); class UserProfileBloc extends Cubit with HydratedMixin { final BreezServer _breezServer; @@ -24,10 +24,10 @@ class UserProfileBloc extends Cubit with HydratedMixin { this._notifications, ) : super(UserProfileState.initial()) { var profile = state; - _log.v("State: ${profile.profileSettings.toJson()}"); + _log.fine("State: ${profile.profileSettings.toJson()}"); final settings = profile.profileSettings; if (settings.color == null || settings.animal == null || settings.name == null) { - _log.v("Profile is missing fields, generating new random ones…"); + _log.fine("Profile is missing fields, generating new random ones…"); final defaultProfile = generateDefaultProfile(); final color = settings.color ?? defaultProfile.color; final animal = settings.animal ?? defaultProfile.animal; @@ -45,11 +45,11 @@ class UserProfileBloc extends Cubit with HydratedMixin { } Future registerForNotifications() async { - _log.v("registerForNotifications"); + _log.fine("registerForNotifications"); String? token = await _notifications.getToken(); if (token != null) { if (token != state.profileSettings.token) { - _log.v("Got a new token, registering…"); + _log.fine("Got a new token, registering…"); var userID = await _breezServer.registerDevice(token, token); emit(state.copyWith( profileSettings: state.profileSettings.copyWith( @@ -59,15 +59,15 @@ class UserProfileBloc extends Cubit with HydratedMixin { ), )); } else { - _log.v("Token is the same as before"); + _log.fine("Token is the same as before"); } } else { - _log.w("Failed to get token"); + _log.warning("Failed to get token"); } } Future uploadImage(List bytes) async { - _log.v("uploadImage ${bytes.length}"); + _log.fine("uploadImage ${bytes.length}"); try { // TODO upload image to server // return await _breezServer.uploadLogo(bytes); @@ -87,7 +87,7 @@ class UserProfileBloc extends Cubit with HydratedMixin { AppMode? appMode, bool? expandPreferences, }) { - _log.v( + _log.fine( "updateProfile $name $color $animal $image $registrationRequested $hideBalance $appMode $expandPreferences"); var profile = state.profileSettings; profile = profile.copyWith( diff --git a/lib/config.dart b/lib/config.dart index 94a488fed..5969ba36f 100644 --- a/lib/config.dart +++ b/lib/config.dart @@ -1,12 +1,12 @@ import 'package:breez_sdk/breez_sdk.dart'; import 'package:breez_sdk/bridge_generated.dart' as sdk; import 'package:c_breez/services/injector.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:path_provider/path_provider.dart'; import 'app_config.dart'; -final _log = FimberLog("Config"); +final _log = Logger("Config"); class Config { static Config? _instance; @@ -24,9 +24,9 @@ class Config { static Future instance({ ServiceInjector? serviceInjector, }) async { - _log.v("Getting Config instance"); + _log.fine("Getting Config instance"); if (_instance == null) { - _log.v("Creating Config instance"); + _log.fine("Creating Config instance"); final injector = serviceInjector ?? ServiceInjector(); final breezLib = injector.breezSDK; final breezConfig = await _getBundledConfig(); @@ -44,7 +44,7 @@ class Config { } static Future _getBundledConfig() async { - _log.v("Getting bundled config"); + _log.fine("Getting bundled config"); return AppConfig(); } @@ -54,7 +54,7 @@ class Config { sdk.NodeConfig nodeConfig, { sdk.EnvironmentType environmentType = sdk.EnvironmentType.Production, }) async { - _log.v("Getting default SDK config for environment: $environmentType"); + _log.fine("Getting default SDK config for environment: $environmentType"); return await breezLib.defaultConfig( envType: environmentType, apiKey: apiKey, @@ -67,7 +67,7 @@ class Config { sdk.Config defaultConf, AppConfig breezConfig, ) async { - _log.v("Getting SDK config"); + _log.fine("Getting SDK config"); return defaultConf.copyWith( maxfeePercent: await _configuredMaxFeePercent(serviceInjector, defaultConf), workingDir: await _workingDir(), @@ -85,7 +85,7 @@ class Config { final configuredMaxFeeEnabled = await preferences.getPaymentOptionsOverrideFeeEnabled(); if (configuredMaxFeeEnabled) { final configuredMaxFeePercent = await preferences.getPaymentOptionsProportionalFee(); - _log.v("Using maxfeePercent from preferences: $configuredMaxFeePercent"); + _log.fine("Using maxfeePercent from preferences: $configuredMaxFeePercent"); return configuredMaxFeePercent; } return defaultConf.maxfeePercent; @@ -99,7 +99,7 @@ class Config { final configuredExemptFeeEnabled = await preferences.getPaymentOptionsOverrideFeeEnabled(); if (configuredExemptFeeEnabled) { final configuredExemptFee = await preferences.getPaymentOptionsExemptFee(); - _log.v("Using exemptMsatFee from preferences: $configuredExemptFee"); + _log.fine("Using exemptMsatFee from preferences: $configuredExemptFee"); return configuredExemptFee; } return defaultConf.exemptfeeMsat; @@ -113,11 +113,11 @@ class Config { final url = await preferences.getMempoolSpaceUrl(); if (url != null) { - _log.v("Using mempoolspace url from preferences: $url"); + _log.fine("Using mempoolspace url from preferences: $url"); return url; } else { final defaultUrl = defaultConf.mempoolspaceUrl; - _log.v("No mempoolspace url in preferences, using default: $defaultUrl"); + _log.fine("No mempoolspace url in preferences, using default: $defaultUrl"); return defaultUrl; } } @@ -125,7 +125,7 @@ class Config { static Future _workingDir() async { final workingDir = await getApplicationDocumentsDirectory(); final path = workingDir.path; - _log.v("Using workingDir: $path"); + _log.fine("Using workingDir: $path"); return path; } } diff --git a/lib/handlers/connectivity_handler.dart b/lib/handlers/connectivity_handler.dart index c323cb019..6a4f56a1c 100644 --- a/lib/handlers/connectivity_handler.dart +++ b/lib/handlers/connectivity_handler.dart @@ -8,11 +8,11 @@ import 'package:c_breez/handlers/handler.dart'; import 'package:c_breez/handlers/handler_context_provider.dart'; import 'package:c_breez/theme/theme_provider.dart' as theme; import 'package:connectivity_plus/connectivity_plus.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("ConnectivityHandler"); +final _log = Logger("ConnectivityHandler"); class ConnectivityHandler extends Handler { StreamSubscription? _subscription; @@ -38,7 +38,7 @@ class ConnectivityHandler extends Handler { } void _listen(ConnectivityState connectivityState) async { - _log.v("Received connectivityState $connectivityState"); + _log.fine("Received connectivityState $connectivityState"); if (connectivityState.lastStatus == ConnectivityResult.none) { showNoInternetConnectionFlushbar(); } else { @@ -50,7 +50,7 @@ class ConnectivityHandler extends Handler { dismissFlushbarIfNeed(); final context = contextProvider?.getBuildContext(); if (context == null) { - _log.v("Skipping connection flushbar as context is null"); + _log.fine("Skipping connection flushbar as context is null"); return; } _flushbar = _getNoConnectionFlushbar(context); diff --git a/lib/handlers/input_handler.dart b/lib/handlers/input_handler.dart index a68f529c2..5c78ff6b2 100644 --- a/lib/handlers/input_handler.dart +++ b/lib/handlers/input_handler.dart @@ -15,11 +15,11 @@ import 'package:c_breez/widgets/flushbar.dart'; import 'package:c_breez/widgets/loader.dart'; import 'package:c_breez/widgets/payment_dialogs/payment_request_dialog.dart'; import 'package:c_breez/widgets/route.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("InputHandler"); +final _log = Logger("InputHandler"); class InputHandler extends Handler { final GlobalKey firstPaymentItemKey; @@ -56,9 +56,9 @@ class InputHandler extends Handler { } void _listen(InputState inputState) { - _log.v("Input state changed: $inputState"); + _log.fine("Input state changed: $inputState"); if (_handlingRequest) { - _log.v("Already handling request, skipping state change"); + _log.fine("Already handling request, skipping state change"); return; } @@ -71,7 +71,7 @@ class InputHandler extends Handler { }) .whenComplete(() => _handlingRequest = false) .onError((error, _) { - _log.e("Input state error", ex: error); + _log.severe("Input state error", error); _handlingRequest = false; _setLoading(false); if (error != null) { @@ -79,29 +79,29 @@ class InputHandler extends Handler { if (context != null) { showFlushbar(context, message: extractExceptionMessage(error, context.texts())); } else { - _log.v("Skipping handling of error: $error because context is null"); + _log.fine("Skipping handling of error: $error because context is null"); } } }); } void handleResult(result) { - _log.v("Input state handled: $result"); + _log.fine("Input state handled: $result"); if (result is LNURLPageResult && result.protocol != null) { final context = contextProvider?.getBuildContext(); if (context != null) { handleLNURLPageResult(context, result); } else { - _log.v("Skipping handling of result: $result because context is null"); + _log.fine("Skipping handling of result: $result because context is null"); } } } Future handleInputData(dynamic parsedInput) async { - _log.v("handle input $parsedInput"); + _log.fine("handle input $parsedInput"); final context = contextProvider?.getBuildContext(); if (context == null) { - _log.v("Not handling input $parsedInput because context is null"); + _log.fine("Not handling input $parsedInput because context is null"); return; } @@ -118,7 +118,7 @@ class InputHandler extends Handler { } Future handleInvoice(BuildContext context, Invoice invoice) async { - _log.v("handle invoice $invoice"); + _log.fine("handle invoice $invoice"); return await showDialog( useRootNavigator: false, context: context, @@ -132,7 +132,7 @@ class InputHandler extends Handler { } Future handleNodeID(BuildContext context, String nodeID) async { - _log.v("handle node id $nodeID"); + _log.fine("handle node id $nodeID"); return await Navigator.of(context).push( FadeInRoute( builder: (_) => SpontaneousPaymentPage( diff --git a/lib/handlers/payment_result_handler.dart b/lib/handlers/payment_result_handler.dart index 482b12503..09d4ea561 100644 --- a/lib/handlers/payment_result_handler.dart +++ b/lib/handlers/payment_result_handler.dart @@ -7,12 +7,12 @@ import 'package:c_breez/bloc/account/payment_result.dart'; import 'package:c_breez/handlers/handler.dart'; import 'package:c_breez/handlers/handler_context_provider.dart'; import 'package:c_breez/widgets/flushbar.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:rxdart/rxdart.dart'; -final _log = FimberLog("PaymentResultHandler"); +final _log = Logger("PaymentResultHandler"); class PaymentResultHandler extends Handler { StreamSubscription? _subscription; @@ -20,7 +20,7 @@ class PaymentResultHandler extends Handler { @override void init(HandlerContextProvider contextProvider) { super.init(contextProvider); - _log.v("PaymentResultHandler inited"); + _log.fine("PaymentResultHandler inited"); _subscription = contextProvider .getBuildContext()! .read() @@ -37,10 +37,10 @@ class PaymentResultHandler extends Handler { } void _listen(PaymentResult paymentResult) async { - _log.v("Received paymentResult: $paymentResult"); + _log.fine("Received paymentResult: $paymentResult"); final context = contextProvider?.getBuildContext(); if (context == null) { - _log.w("Failed to proceed because context is null"); + _log.warning("Failed to proceed because context is null"); return; } @@ -57,7 +57,7 @@ class PaymentResultHandler extends Handler { ), ); } else if (paymentResult.error != null) { - _log.v("paymentResult error: ${paymentResult.error}"); + _log.fine("paymentResult error: ${paymentResult.error}"); showFlushbar( context, message: paymentResult.errorMessage(), diff --git a/lib/logger.dart b/lib/logger.dart index 288556575..40bf47add 100644 --- a/lib/logger.dart +++ b/lib/logger.dart @@ -3,12 +3,12 @@ library breez.logger; import 'dart:io'; import 'package:archive/archive_io.dart'; -import 'package:fimber_io/fimber_io.dart'; import 'package:flutter/foundation.dart'; +import 'package:logging/logging.dart'; import 'package:path_provider/path_provider.dart'; import 'package:share_plus/share_plus.dart'; -final _log = FimberLog("logger"); +final _log = Logger("logger"); void shareLog() async { final appDir = await getApplicationDocumentsDirectory(); @@ -23,71 +23,63 @@ void shareLog() async { class BreezLogger { BreezLogger() { - final logLevels = [ - "V", // log.v Verbose - "D", // log.d Debug - "I", // log.i Info - "W", // log.w Warning - "E", // log.e Error - ]; + Logger.root.level = Level.ALL; if (kDebugMode) { - Fimber.plantTree(DebugTree( - logLevels: logLevels, - )); + Logger.root.onRecord.listen((record) { + print(_recordToString(record)); + }); } - getApplicationDocumentsDirectory().then( - (appDir) { - _pruneLogs(appDir); - final tokens = [ - CustomFormatTree.timeStampToken, - CustomFormatTree.levelToken, - CustomFormatTree.tagToken, - CustomFormatTree.messageToken, - CustomFormatTree.fileNameToken, - CustomFormatTree.lineNumberToken, - CustomFormatTree.filePathToken, - CustomFormatTree.exceptionMsgToken, - CustomFormatTree.exceptionStackToken, - ]; - Fimber.plantTree( - SizeRollingFileTree( - DataSize(megabytes: 10), - filenamePrefix: "${appDir.path}/logs/c_breez.", - filenamePostfix: ".log", - logLevels: logLevels, - logFormat: tokens.fold("", (p, e) => p == "" ? e : "$p :: $e"), - ), - ); - FlutterError.onError = (FlutterErrorDetails details) async { - FlutterError.presentError(details); - final name = details.context?.name ?? "FlutterError"; - final exception = details.exceptionAsString(); - _log.e("$exception --$name", ex: details, stacktrace: details.stack); - }; - }, - ); + getApplicationDocumentsDirectory().then((appDir) { + _pruneLogs(appDir); + final file = File("${_logDir(appDir)}/${DateTime.now().millisecondsSinceEpoch}.log"); + try { + file.createSync(recursive: true); + } catch (e) { + _log.severe("Failed to create log file", e); + return; + } + final sync = file.openWrite(mode: FileMode.append); + Logger.root.onRecord.listen((record) { + sync.writeln(_recordToString(record)); + }, onDone: () { + sync.flush(); + sync.close(); + }); + }); + + FlutterError.onError = (FlutterErrorDetails details) async { + FlutterError.presentError(details); + final name = details.context?.name ?? "FlutterError"; + final exception = details.exceptionAsString(); + _log.severe("$exception -- $name", details, details.stack); + }; } -} -void _pruneLogs(Directory appDir) { - final loggingFolder = Directory("${appDir.path}/logs/"); - if (loggingFolder.existsSync()) { - // Get and sort log files by modified date - List filesToBePruned = loggingFolder - .listSync(followLinks: false) - .where((e) => e.path.endsWith('.log')) - .toList() - ..sort((l, r) => l.statSync().modified.compareTo(r.statSync().modified)); - // Delete all except last 2 logs - if (filesToBePruned.length > 2) { - filesToBePruned.removeRange( - filesToBePruned.length - 2, - filesToBePruned.length, - ); - for (var logFile in filesToBePruned) { - logFile.delete(); + String _recordToString(LogRecord record) => + "[${record.loggerName}] {${record.level.name}} (${record.time}) : ${record.message}"; + + String _logDir(Directory appDir) => "${appDir.path}/logs/"; + + void _pruneLogs(Directory appDir) { + final loggingFolder = Directory(_logDir(appDir)); + if (loggingFolder.existsSync()) { + // Get and sort log files by modified date + List filesToBePruned = loggingFolder + .listSync(followLinks: false) + .where((e) => e.path.endsWith('.log')) + .toList() + ..sort((l, r) => l.statSync().modified.compareTo(r.statSync().modified)); + // Delete all except last 10 logs + if (filesToBePruned.length > 10) { + filesToBePruned.removeRange( + filesToBePruned.length - 10, + filesToBePruned.length, + ); + for (var logFile in filesToBePruned) { + logFile.delete(); + } } } } diff --git a/lib/main.dart b/lib/main.dart index a419ba5a9..101ddee80 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -25,7 +25,7 @@ import 'package:c_breez/logger.dart'; import 'package:c_breez/services/injector.dart'; import 'package:c_breez/user_app.dart'; import 'package:c_breez/utils/date.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/cupertino.dart'; @@ -38,7 +38,7 @@ import 'package:path_provider/path_provider.dart'; import 'bloc/network/network_settings_bloc.dart'; -final _log = FimberLog("Main"); +final _log = Logger("Main"); void main() async { // runZonedGuarded wrapper is required to log Dart errors. @@ -124,7 +124,7 @@ void main() async { ); }, (error, stackTrace) async { if (error is! FlutterErrorDetails) { - _log.e("FlutterError: $error", ex: error, stacktrace: stackTrace); + _log.severe("FlutterError: $error", error, stackTrace); } }); } diff --git a/lib/models/payment_minutiae.dart b/lib/models/payment_minutiae.dart index 9d73f3bc1..8b47a8654 100644 --- a/lib/models/payment_minutiae.dart +++ b/lib/models/payment_minutiae.dart @@ -4,10 +4,10 @@ import 'dart:typed_data'; import 'package:breez_sdk/bridge_generated.dart'; import 'package:breez_translations/generated/breez_translations.dart'; import 'package:c_breez/utils/extensions/breez_pos_message_extractor.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; -final _log = FimberLog("PaymentDetails"); +final _log = Logger("PaymentDetails"); /// Hold formatted data from Payment to be displayed in the UI, using the minutiae noun instead of details or /// info to avoid conflicts and make it easier to differentiate when reading the code. @@ -98,27 +98,27 @@ class _PaymentMinutiaeFactory { try { final parsed = json.decode(metadata); if (parsed is! List) { - _log.w("Unknown runtime type of $parsed for $metadata"); + _log.warning("Unknown runtime type of $parsed for $metadata"); return; } for (var item in parsed) { if (item is! List || item.length != 2) { - _log.w("Unknown runtime type of item $item"); + _log.warning("Unknown runtime type of item $item"); continue; } final key = item[0]; final value = item[1]; if (key is! String) { - _log.w("Unknown runtime type of key $key"); + _log.warning("Unknown runtime type of key $key"); continue; } _metadataMap[key] = value; } } catch (e) { - _log.w("Failed to parse metadata: $metadata", ex: e); + _log.warning("Failed to parse metadata: $metadata", e); } } @@ -246,7 +246,7 @@ class _PaymentMinutiaeFactory { try { bytes = base64Decode(base64String); } catch (e) { - _log.w("Failed to decode image: $base64String", ex: e); + _log.warning("Failed to decode image: $base64String", e); return null; } if (bytes.isNotEmpty) { diff --git a/lib/routes/buy_bitcoin/moonpay/moonpay_webview.dart b/lib/routes/buy_bitcoin/moonpay/moonpay_webview.dart index 7f6719b8f..1eb01626f 100644 --- a/lib/routes/buy_bitcoin/moonpay/moonpay_webview.dart +++ b/lib/routes/buy_bitcoin/moonpay/moonpay_webview.dart @@ -1,12 +1,12 @@ import 'package:c_breez/bloc/buy_bitcoin/moonpay/moonpay_bloc.dart'; import 'package:c_breez/bloc/buy_bitcoin/moonpay/moonpay_state.dart'; import 'package:c_breez/routes/buy_bitcoin/moonpay/moonpay_loading.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; -final _log = FimberLog("MoonpayWebView"); +final _log = Logger("MoonpayWebView"); class MoonpayWebView extends StatelessWidget { final String url; @@ -32,27 +32,27 @@ class MoonpayWebView extends StatelessWidget { url: WebUri(url), ), onLoadStart: (controller, url) { - _log.v("onLoadStart url: $url"); + _log.fine("onLoadStart url: $url"); context.read().updateWebViewStatus(WebViewStatus.loading); }, onLoadStop: (controller, url) { - _log.v("onLoadStop url: $url"); + _log.fine("onLoadStop url: $url"); context.read().updateWebViewStatus(WebViewStatus.success); }, onReceivedError: (controller, request, error) { - _log.w("onReceivedError error: $error", ex: error); + _log.warning("onReceivedError error: $error", error); if (error.type == WebResourceErrorType.UNKNOWN) { - _log.v("Ignoring unknown error"); + _log.fine("Ignoring unknown error"); return; } context.read().updateWebViewStatus(WebViewStatus.error); }, onReceivedHttpError: (controller, request, error) { - _log.w("onReceivedHttpError error: $error", ex: error); + _log.warning("onReceivedHttpError error: $error", error); context.read().updateWebViewStatus(WebViewStatus.error); }, onConsoleMessage: (controller, consoleMessage) { - _log.v("onConsoleMessage: $consoleMessage"); + _log.fine("onConsoleMessage: $consoleMessage"); }, ), ], diff --git a/lib/routes/create_invoice/create_invoice_page.dart b/lib/routes/create_invoice/create_invoice_page.dart index a01fde1df..202eeb033 100644 --- a/lib/routes/create_invoice/create_invoice_page.dart +++ b/lib/routes/create_invoice/create_invoice_page.dart @@ -21,12 +21,12 @@ import 'package:c_breez/widgets/keyboard_done_action.dart'; import 'package:c_breez/widgets/receivable_btc_box.dart'; import 'package:c_breez/widgets/single_button_bottom_bar.dart'; import 'package:c_breez/widgets/transparent_page_route.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("CreateInvoicePage"); +final _log = Logger("CreateInvoicePage"); class CreateInvoicePage extends StatefulWidget { final Function(LNURLPageResult? result)? onFinish; @@ -170,7 +170,7 @@ class CreateInvoicePageState extends State { BuildContext context, LnUrlWithdrawRequestData data, ) async { - _log.v("Withdraw request: description=${data.defaultDescription}, k1=${data.k1}, " + _log.fine("Withdraw request: description=${data.defaultDescription}, k1=${data.k1}, " "min=${data.minWithdrawable}, max=${data.maxWithdrawable}"); final CurrencyBloc currencyBloc = context.read(); @@ -192,7 +192,7 @@ class CreateInvoicePageState extends State { } Future _createInvoice(BuildContext context) async { - _log.v("Create invoice: description=${_descriptionController.text}, amount=${_amountController.text}"); + _log.fine("Create invoice: description=${_descriptionController.text}, amount=${_amountController.text}"); final navigator = Navigator.of(context); final currentRoute = ModalRoute.of(navigator.context)!; final accountBloc = context.read(); @@ -206,7 +206,7 @@ class CreateInvoicePageState extends State { Widget dialog = FutureBuilder( future: receivePaymentResponse, builder: (BuildContext context, AsyncSnapshot snapshot) { - _log.v("Building QrCodeDialog with invoice: ${snapshot.data}, error: ${snapshot.error}"); + _log.fine("Building QrCodeDialog with invoice: ${snapshot.data}, error: ${snapshot.error}"); return QrCodeDialog( snapshot.data, snapshot.error, @@ -230,7 +230,7 @@ class CreateInvoicePageState extends State { ModalRoute currentRoute, NavigatorState navigator, ) { - _log.v("Payment finished: $result"); + _log.fine("Payment finished: $result"); if (result == true) { if (currentRoute.isCurrent) { navigator.push( diff --git a/lib/routes/create_invoice/qr_code_dialog.dart b/lib/routes/create_invoice/qr_code_dialog.dart index 9c8b3ce7f..ef752ba3d 100644 --- a/lib/routes/create_invoice/qr_code_dialog.dart +++ b/lib/routes/create_invoice/qr_code_dialog.dart @@ -10,12 +10,12 @@ import 'package:c_breez/routes/create_invoice/widgets/loading_or_error.dart'; import 'package:c_breez/services/injector.dart'; import 'package:c_breez/utils/exceptions.dart'; import 'package:c_breez/widgets/flushbar.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:share_plus/share_plus.dart'; -final _log = FimberLog("QrCodeDialog"); +final _log = Logger("QrCodeDialog"); class QrCodeDialog extends StatefulWidget { final ReceivePaymentResponse? receivePaymentResponse; @@ -69,7 +69,7 @@ class QrCodeDialogState extends State with SingleTickerProviderSta } }); }).catchError((e) { - _log.w("Failed to track payment", ex: e); + _log.warning("Failed to track payment", e); showFlushbar(context, message: extractExceptionMessage(e, context.texts())); onFinish(false); }); @@ -177,7 +177,7 @@ class QrCodeDialogState extends State with SingleTickerProviderSta } void onFinish(dynamic result) { - _log.v("onFinish $result, mounted: $mounted, _currentRoute: ${_currentRoute?.isCurrent}"); + _log.fine("onFinish $result, mounted: $mounted, _currentRoute: ${_currentRoute?.isCurrent}"); if (mounted && _currentRoute != null && _currentRoute!.isCurrent) { Navigator.removeRoute(context, _currentRoute!); } diff --git a/lib/routes/create_invoice/widgets/expiry_and_fee_message.dart b/lib/routes/create_invoice/widgets/expiry_and_fee_message.dart index fafc1ec2a..29597e92c 100644 --- a/lib/routes/create_invoice/widgets/expiry_and_fee_message.dart +++ b/lib/routes/create_invoice/widgets/expiry_and_fee_message.dart @@ -3,11 +3,11 @@ import 'package:c_breez/bloc/currency/currency_bloc.dart'; import 'package:c_breez/bloc/currency/currency_state.dart'; import 'package:c_breez/theme/theme_extensions.dart'; import 'package:c_breez/widgets/warning_box.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final log = FimberLog("ExpiryAndFeeMessage"); +final log = Logger("ExpiryAndFeeMessage"); class ExpiryAndFeeMessage extends StatelessWidget { final int? lspFees; diff --git a/lib/routes/dev/command_line_interface.dart b/lib/routes/dev/command_line_interface.dart index a04afcc38..f12e4d563 100644 --- a/lib/routes/dev/command_line_interface.dart +++ b/lib/routes/dev/command_line_interface.dart @@ -4,12 +4,12 @@ import 'dart:io'; import 'package:c_breez/routes/dev/widget/command_list.dart'; import 'package:c_breez/services/injector.dart'; import 'package:c_breez/theme/theme_provider.dart' as theme; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; import 'package:share_plus/share_plus.dart'; -final _log = FimberLog("CommandsList"); +final _log = Logger("CommandsList"); class CommandLineInterface extends StatefulWidget { final GlobalKey scaffoldKey; @@ -151,7 +151,7 @@ class _CommandLineInterfaceState extends State { } void _sendCommand(String command) async { - _log.v("Send command: $command"); + _log.fine("Send command: $command"); if (command.isNotEmpty) { FocusScope.of(context).requestFocus(FocusNode()); setState(() { @@ -163,7 +163,7 @@ class _CommandLineInterfaceState extends State { try { var commandArgs = command.split(RegExp(r"\s")); if (commandArgs.isEmpty) { - _log.v("Command args is empty, skipping"); + _log.fine("Command args is empty, skipping"); setState(() { isLoading = false; }); @@ -178,11 +178,11 @@ class _CommandLineInterfaceState extends State { case 'listInvoices': case 'closeAllChannels': final command = commandArgs[0].toLowerCase(); - _log.v("executing command: $command"); + _log.fine("executing command: $command"); final answer = await _breezLib.executeCommand(command: command); - _log.v("Received answer: $answer"); + _log.fine("Received answer: $answer"); reply = encoder.convert(answer); - _log.v("Reply: $reply"); + _log.fine("Reply: $reply"); break; default: throw "This command is not supported yet."; @@ -195,7 +195,7 @@ class _CommandLineInterfaceState extends State { isLoading = false; }); } catch (error) { - _log.w("Error happening", ex: error); + _log.warning("Error happening", error); setState(() { _showDefaultCommands = false; _cliText = error.toString(); diff --git a/lib/routes/home/account_page.dart b/lib/routes/home/account_page.dart index 7fa8994a8..97ad81ad1 100644 --- a/lib/routes/home/account_page.dart +++ b/lib/routes/home/account_page.dart @@ -15,14 +15,14 @@ import 'package:c_breez/routes/home/widgets/payments_filter/payments_filter_sliv import 'package:c_breez/routes/home/widgets/payments_list/payments_list.dart'; import 'package:c_breez/routes/home/widgets/status_text.dart'; import 'package:c_breez/theme/theme_provider.dart' as theme; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; const _kFilterMaxSize = 64.0; const _kPaymentListItemHeight = 72.0; -final _log = FimberLog("AccountPage"); +final _log = Logger("AccountPage"); class AccountPage extends StatelessWidget { final GlobalKey firstPaymentItemKey; @@ -40,7 +40,7 @@ class AccountPage extends StatelessWidget { builder: (context, accountState) { return BlocBuilder( builder: (context, userModel) { - _log.v("AccountPage build with ${accountState.payments.length} payments"); + _log.fine("AccountPage build with ${accountState.payments.length} payments"); return Container( color: Theme.of(context).customData.dashboardBgColor, child: _build( diff --git a/lib/routes/home/widgets/bottom_actions_bar/enter_payment_info_dialog.dart b/lib/routes/home/widgets/bottom_actions_bar/enter_payment_info_dialog.dart index 942b7e1fe..4af29d877 100644 --- a/lib/routes/home/widgets/bottom_actions_bar/enter_payment_info_dialog.dart +++ b/lib/routes/home/widgets/bottom_actions_bar/enter_payment_info_dialog.dart @@ -4,11 +4,11 @@ import 'package:c_breez/bloc/input/input_bloc.dart'; import 'package:c_breez/theme/theme_provider.dart' as theme; import 'package:c_breez/widgets/flushbar.dart'; import 'package:c_breez/widgets/loader.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("EnterPaymentInfoDialog"); +final _log = Logger("EnterPaymentInfoDialog"); class EnterPaymentInfoDialog extends StatefulWidget { final GlobalKey paymentItemKey; @@ -164,7 +164,7 @@ class EnterPaymentInfoDialogState extends State { } } catch (error) { _setLoading(false); - _log.w(error.toString(), ex: error); + _log.warning(error.toString(), error); _setValidatorErrorMessage(texts.payment_info_dialog_error); } finally { _setLoading(false); @@ -208,7 +208,7 @@ class EnterPaymentInfoDialogState extends State { try { _setValidatorErrorMessage(""); final inputType = await context.read().parseInput(input: input); - _log.v("Parsed input type: '${inputType.runtimeType.toString()}"); + _log.fine("Parsed input type: '${inputType.runtimeType.toString()}"); // Can't compare against a list of InputType as runtime type comparison is a bit tricky with binding generated enums if (!(inputType is InputType_Bolt11 || inputType is InputType_LnUrlPay || diff --git a/lib/routes/home/widgets/payments_filter/payment_filter_exporter.dart b/lib/routes/home/widgets/payments_filter/payment_filter_exporter.dart index 56fb198c7..c88896f6e 100644 --- a/lib/routes/home/widgets/payments_filter/payment_filter_exporter.dart +++ b/lib/routes/home/widgets/payments_filter/payment_filter_exporter.dart @@ -7,13 +7,13 @@ import 'package:c_breez/bloc/currency/currency_bloc.dart'; import 'package:c_breez/theme/theme_provider.dart'; import 'package:c_breez/widgets/flushbar.dart'; import 'package:c_breez/widgets/loader.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:share_plus/share_plus.dart'; class PaymentmentFilterExporter extends StatelessWidget { - final _log = FimberLog("PaymentmentFilterExporter"); + final _log = Logger("PaymentmentFilterExporter"); final PaymentTypeFilter filter; PaymentmentFilterExporter( @@ -87,7 +87,7 @@ class PaymentmentFilterExporter extends StatelessWidget { if (loaderRoute.isActive) { navigator.removeRoute(loaderRoute); } - _log.e("Received error: $error"); + _log.severe("Received error: $error"); showFlushbar( context, message: texts.payments_filter_action_export_failed, diff --git a/lib/routes/home/widgets/payments_list/payment_details_dialog.dart b/lib/routes/home/widgets/payments_list/payment_details_dialog.dart index 8ad93d597..d17710272 100644 --- a/lib/routes/home/widgets/payments_list/payment_details_dialog.dart +++ b/lib/routes/home/widgets/payments_list/payment_details_dialog.dart @@ -12,13 +12,13 @@ import 'package:c_breez/routes/home/widgets/payments_list/dialog/payment_details import 'package:c_breez/routes/home/widgets/payments_list/dialog/payment_details_dialog_preimage.dart'; import 'package:c_breez/routes/home/widgets/payments_list/dialog/payment_details_dialog_success_action.dart'; import 'package:c_breez/routes/home/widgets/payments_list/dialog/payment_details_dialog_title.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; final AutoSizeGroup _labelGroup = AutoSizeGroup(); final AutoSizeGroup _valueGroup = AutoSizeGroup(); -final _log = FimberLog("PaymentDetailsDialog"); +final _log = Logger("PaymentDetailsDialog"); class PaymentDetailsDialog extends StatelessWidget { final PaymentMinutiae paymentMinutiae; @@ -27,7 +27,7 @@ class PaymentDetailsDialog extends StatelessWidget { super.key, required this.paymentMinutiae, }) { - _log.v("PaymentDetailsDialog for payment: ${paymentMinutiae.id}"); + _log.fine("PaymentDetailsDialog for payment: ${paymentMinutiae.id}"); } @override diff --git a/lib/routes/home/widgets/qr_action_button.dart b/lib/routes/home/widgets/qr_action_button.dart index 9c265bde7..4b4d74370 100644 --- a/lib/routes/home/widgets/qr_action_button.dart +++ b/lib/routes/home/widgets/qr_action_button.dart @@ -4,12 +4,12 @@ import 'package:c_breez/bloc/lsp/lsp_bloc.dart'; import 'package:c_breez/bloc/lsp/lsp_state.dart'; import 'package:c_breez/theme/theme_provider.dart' as theme; import 'package:c_breez/widgets/flushbar.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/svg.dart'; -final _log = FimberLog("QrActionButton"); +final _log = Logger("QrActionButton"); class QrActionButton extends StatelessWidget { final GlobalKey firstPaymentItemKey; @@ -47,10 +47,10 @@ class QrActionButton extends StatelessWidget { final texts = context.texts(); InputBloc inputBloc = context.read(); - _log.v("Start qr code scan"); + _log.fine("Start qr code scan"); Navigator.pushNamed(context, "/qr_scan").then( (barcode) { - _log.v("Scanned string: '$barcode'"); + _log.fine("Scanned string: '$barcode'"); if (barcode == null) return; if (barcode.isEmpty) { showFlushbar( diff --git a/lib/routes/initial_walkthrough/initial_walkthrough.dart b/lib/routes/initial_walkthrough/initial_walkthrough.dart index 2604b5c4e..9021e7073 100644 --- a/lib/routes/initial_walkthrough/initial_walkthrough.dart +++ b/lib/routes/initial_walkthrough/initial_walkthrough.dart @@ -7,7 +7,7 @@ import 'package:c_breez/theme/theme_provider.dart' as theme; import 'package:c_breez/utils/exceptions.dart'; import 'package:c_breez/widgets/flushbar.dart'; import 'package:c_breez/widgets/loader.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:theme_provider/theme_provider.dart'; @@ -19,7 +19,7 @@ class InitialWalkthroughPage extends StatefulWidget { class InitialWalkthroughPageState extends State with TickerProviderStateMixin, WidgetsBindingObserver { - final _log = FimberLog("InitialWalkthrough"); + final _log = Logger("InitialWalkthrough"); AnimationController? _controller; Animation? _animation; @@ -139,7 +139,7 @@ class InitialWalkthroughPageState extends State } void _letsBreez(BuildContext context) async { - _log.v("Lets breez"); + _log.fine("Lets breez"); bool approved = await showDialog( useRootNavigator: false, context: context, @@ -153,7 +153,7 @@ class InitialWalkthroughPageState extends State void connect({String? mnemonic}) async { final isRestore = mnemonic != null; - _log.v("${isRestore ? "Restore" : "Starting new"} node"); + _log.fine("${isRestore ? "Restore" : "Starting new"} node"); final texts = context.texts(); final accountBloc = context.read(); final navigator = Navigator.of(context); @@ -164,7 +164,7 @@ class InitialWalkthroughPageState extends State try { await accountBloc.connect(mnemonic: mnemonic ?? bip39.generateMnemonic(strength: 128)); } catch (error) { - _log.i("Failed to ${isRestore ? "restore" : "registe"} node", ex: error); + _log.info("Failed to ${isRestore ? "restore" : "registe"} node", error); if (isRestore) { _restoreNodeFromMnemonicSeed(initialWords: mnemonic.split(" ")); } @@ -181,7 +181,7 @@ class InitialWalkthroughPageState extends State void _restoreNodeFromMnemonicSeed({ List? initialWords, }) async { - _log.v("Restore node from mnemonic seed"); + _log.fine("Restore node from mnemonic seed"); String? mnemonic = await _getMnemonic(initialWords: initialWords); if (mnemonic != null) { connect(mnemonic: mnemonic); @@ -191,7 +191,7 @@ class InitialWalkthroughPageState extends State Future _getMnemonic({ List? initialWords, }) async { - _log.v("Get mnemonic, initialWords: ${initialWords?.length}"); + _log.fine("Get mnemonic, initialWords: ${initialWords?.length}"); return await Navigator.of(context).pushNamed( "/enter_mnemonics", arguments: initialWords, diff --git a/lib/routes/lnurl/auth/lnurl_auth_handler.dart b/lib/routes/lnurl/auth/lnurl_auth_handler.dart index 36fac85b0..f6f34bb8d 100644 --- a/lib/routes/lnurl/auth/lnurl_auth_handler.dart +++ b/lib/routes/lnurl/auth/lnurl_auth_handler.dart @@ -5,15 +5,16 @@ import 'package:c_breez/routes/lnurl/auth/login_text.dart'; import 'package:c_breez/routes/lnurl/widgets/lnurl_page_result.dart'; import 'package:c_breez/widgets/error_dialog.dart'; import 'package:c_breez/widgets/loader.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +final _log = Logger("handleLNURLAuthRequest"); + Future handleAuthRequest( BuildContext context, LnUrlAuthRequestData requestData, ) async { - final log = FimberLog("handleLNURLAuthRequest"); return promptAreYouSure(context, null, LoginText(domain: requestData.domain)).then( (permitted) async { if (permitted == true) { @@ -24,20 +25,20 @@ Future handleAuthRequest( try { final resp = await context.read().lnurlAuth(reqData: requestData); if (resp is LnUrlCallbackStatus_Ok) { - log.v("LNURL auth success"); + _log.fine("LNURL auth success"); return const LNURLPageResult(protocol: LnUrlProtocol.Auth); } else if (resp is LnUrlCallbackStatus_ErrorStatus) { - log.v("LNURL auth failed: ${resp.data.reason}"); + _log.fine("LNURL auth failed: ${resp.data.reason}"); return LNURLPageResult(protocol: LnUrlProtocol.Auth, error: resp.data.reason); } else { - log.w("Unknown response from lnurlAuth: $resp"); + _log.warning("Unknown response from lnurlAuth: $resp"); return LNURLPageResult( protocol: LnUrlProtocol.Auth, error: texts.lnurl_payment_page_unknown_error, ); } } catch (e) { - log.w("Error authenticating LNURL auth", ex: e); + _log.warning("Error authenticating LNURL auth", e); if (loaderRoute.isActive) { navigator.removeRoute(loaderRoute); } @@ -54,9 +55,8 @@ Future handleAuthRequest( } void handleLNURLAuthPageResult(BuildContext context, LNURLPageResult result) { - final log = FimberLog("handleLNURLAuthPageResult"); if (result.hasError) { - log.v("Handle LNURL auth page result with error '${result.error}'"); + _log.fine("Handle LNURL auth page result with error '${result.error}'"); promptError( context, context.texts().lnurl_webview_error_title, diff --git a/lib/routes/lnurl/lnurl_invoice_delegate.dart b/lib/routes/lnurl/lnurl_invoice_delegate.dart index 6ad598caa..a914e56b3 100644 --- a/lib/routes/lnurl/lnurl_invoice_delegate.dart +++ b/lib/routes/lnurl/lnurl_invoice_delegate.dart @@ -5,38 +5,38 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/routes/lnurl/auth/lnurl_auth_handler.dart'; import 'package:c_breez/routes/lnurl/payment/lnurl_payment_handler.dart'; import 'package:c_breez/routes/lnurl/withdraw/lnurl_withdraw_handler.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'widgets/lnurl_page_result.dart'; -final _log = FimberLog("handleLNURL"); +final _log = Logger("handleLNURL"); Future handleLNURL( BuildContext context, GlobalKey firstPaymentItemKey, dynamic requestData, ) { - _log.v("Handling lnurl requestData: $requestData"); + _log.fine("Handling lnurl requestData: $requestData"); if (requestData is LnUrlPayRequestData) { - _log.v("Handling payParams: $requestData"); + _log.fine("Handling payParams: $requestData"); return handlePayRequest(context, firstPaymentItemKey, requestData); } else if (requestData is LnUrlWithdrawRequestData) { - _log.v("Handling withdrawalParams: $requestData"); + _log.fine("Handling withdrawalParams: $requestData"); return handleWithdrawRequest(context, requestData); } else if (requestData is LnUrlAuthRequestData) { - _log.v("Handling lnurl auth: $requestData"); + _log.fine("Handling lnurl auth: $requestData"); return handleAuthRequest(context, requestData); } else if (requestData is LnUrlErrorData) { - _log.v("Handling lnurl error: $requestData"); + _log.fine("Handling lnurl error: $requestData"); throw requestData.reason; } - _log.w("Unsupported lnurl $requestData"); + _log.warning("Unsupported lnurl $requestData"); throw context.texts().lnurl_error_unsupported; } void handleLNURLPageResult(BuildContext context, LNURLPageResult result) { - _log.v("handle $result"); + _log.fine("handle $result"); switch (result.protocol) { case LnUrlProtocol.Pay: handleLNURLPaymentPageResult(context, result); diff --git a/lib/routes/lnurl/payment/lnurl_payment_dialog.dart b/lib/routes/lnurl/payment/lnurl_payment_dialog.dart index 6586062bf..5f00ee3e3 100644 --- a/lib/routes/lnurl/payment/lnurl_payment_dialog.dart +++ b/lib/routes/lnurl/payment/lnurl_payment_dialog.dart @@ -6,11 +6,11 @@ import 'package:c_breez/bloc/currency/currency_bloc.dart'; import 'package:c_breez/models/currency.dart'; import 'package:c_breez/routes/lnurl/payment/lnurl_payment_info.dart'; import 'package:c_breez/utils/fiat_conversion.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("LNURLPaymentDialog"); +final _log = Logger("LNURLPaymentDialog"); class LNURLPaymentDialog extends StatefulWidget { final sdk.LnUrlPayRequestData requestData; @@ -147,7 +147,7 @@ class LNURLPaymentDialogState extends State { ), onPressed: () { final amount = widget.requestData.maxSendable ~/ 1000; - _log.v("LNURL payment of $amount sats where " + _log.fine("LNURL payment of $amount sats where " "min is ${widget.requestData.minSendable} msats " "and max is ${widget.requestData.maxSendable} msats."); Navigator.pop(context, LNURLPaymentInfo(amount: amount)); diff --git a/lib/routes/lnurl/payment/lnurl_payment_handler.dart b/lib/routes/lnurl/payment/lnurl_payment_handler.dart index 8be047595..a2e11e65d 100644 --- a/lib/routes/lnurl/payment/lnurl_payment_handler.dart +++ b/lib/routes/lnurl/payment/lnurl_payment_handler.dart @@ -7,11 +7,11 @@ import 'package:c_breez/routes/lnurl/payment/success_action/success_action_dialo import 'package:c_breez/routes/lnurl/widgets/lnurl_page_result.dart'; import 'package:c_breez/widgets/payment_dialogs/processing_payment_dialog.dart'; import 'package:c_breez/widgets/route.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("handleLNURLPayRequest"); +final _log = Logger("handleLNURLPayRequest"); Future handlePayRequest( BuildContext context, @@ -56,20 +56,20 @@ Future handlePayRequest( ).then((result) { if (result is LnUrlPayResult) { if (result is LnUrlPayResult_EndpointSuccess) { - _log.v("LNURL payment success, action: ${result.data}"); + _log.fine("LNURL payment success, action: ${result.data}"); return LNURLPageResult( protocol: LnUrlProtocol.Pay, successAction: result.data, ); } else if (result is LnUrlPayResult_EndpointError) { - _log.v("LNURL payment failed: ${result.data.reason}"); + _log.fine("LNURL payment failed: ${result.data.reason}"); return LNURLPageResult( protocol: LnUrlProtocol.Pay, error: result.data.reason, ); } } - _log.w("Error sending LNURL payment", ex: result); + _log.warning("Error sending LNURL payment", result); throw LNURLPageResult(error: result).errorMessage; }); } @@ -78,7 +78,7 @@ void handleLNURLPaymentPageResult(BuildContext context, LNURLPageResult result) if (result.successAction != null) { _handleSuccessAction(context, result.successAction!); } else if (result.hasError) { - _log.v("Handle LNURL payment page result with error '${result.error}'"); + _log.fine("Handle LNURL payment page result with error '${result.error}'"); throw Exception(result.errorMessage); } } @@ -88,14 +88,14 @@ Future _handleSuccessAction(BuildContext context, SuccessActionProcessed success String? url; if (successAction is SuccessActionProcessed_Message) { message = successAction.data.message; - _log.v("Handle LNURL payment page result with message action '$message'"); + _log.fine("Handle LNURL payment page result with message action '$message'"); } else if (successAction is SuccessActionProcessed_Url) { message = successAction.data.description; url = successAction.data.url; - _log.v("Handle LNURL payment page result with url action '$message', '$url'"); + _log.fine("Handle LNURL payment page result with url action '$message', '$url'"); } else if (successAction is SuccessActionProcessed_Aes) { message = "${successAction.data.description} ${successAction.data.plaintext}"; - _log.v("Handle LNURL payment page result with aes action '$message'"); + _log.fine("Handle LNURL payment page result with aes action '$message'"); } return showDialog( useRootNavigator: false, diff --git a/lib/routes/lnurl/payment/lnurl_payment_page.dart b/lib/routes/lnurl/payment/lnurl_payment_page.dart index 025947ec2..9277bfd47 100644 --- a/lib/routes/lnurl/payment/lnurl_payment_page.dart +++ b/lib/routes/lnurl/payment/lnurl_payment_page.dart @@ -13,12 +13,12 @@ import 'package:c_breez/widgets/amount_form_field/amount_form_field.dart'; import 'package:c_breez/widgets/back_button.dart' as back_button; import 'package:c_breez/widgets/single_button_bottom_bar.dart'; // import 'package:email_validator/email_validator.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("LNURLPaymentPage"); +final _log = Logger("LNURLPaymentPage"); class LNURLPaymentPage extends StatefulWidget { final sdk.LnUrlPayRequestData requestData; @@ -193,7 +193,7 @@ class LNURLPaymentPageState extends State { final currencyBloc = context.read(); final amount = currencyBloc.state.bitcoinCurrency.parse(_amountController.text); final comment = _commentController.text; - _log.v("LNURL payment of $amount sats where " + _log.fine("LNURL payment of $amount sats where " "min is ${widget.requestData.minSendable} msats " "and max is ${widget.requestData.maxSendable} msats." "with comment $comment"); diff --git a/lib/routes/lnurl/withdraw/lnurl_withdraw_dialog.dart b/lib/routes/lnurl/withdraw/lnurl_withdraw_dialog.dart index c2e3b07c8..2a1c199b3 100644 --- a/lib/routes/lnurl/withdraw/lnurl_withdraw_dialog.dart +++ b/lib/routes/lnurl/withdraw/lnurl_withdraw_dialog.dart @@ -5,11 +5,11 @@ import 'package:c_breez/routes/lnurl/widgets/lnurl_page_result.dart'; import 'package:c_breez/theme/theme_provider.dart' as theme; import 'package:c_breez/utils/exceptions.dart'; import 'package:c_breez/widgets/loading_animated_text.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("LNURLWithdrawDialog"); +final _log = Logger("LNURLWithdrawDialog"); class LNURLWithdrawDialog extends StatefulWidget { final Function(LNURLPageResult? result) onFinish; @@ -52,7 +52,7 @@ class _LNURLWithdrawDialogState extends State with SingleTi _future = _withdraw(context).then((result) { if (result.error == null && mounted) { controller.addStatusListener((status) { - _log.v("Animation status $status"); + _log.fine("Animation status $status"); if (status == AnimationStatus.dismissed && mounted) { finishCalled = true; widget.onFinish(result); @@ -92,7 +92,7 @@ class _LNURLWithdrawDialogState extends State with SingleTi builder: (context, snapshot) { final data = snapshot.data; final error = snapshot.error ?? data?.error; - _log.v("Building with data $data, error $error"); + _log.fine("Building with data $data, error $error"); return Column( mainAxisAlignment: MainAxisAlignment.center, @@ -134,13 +134,13 @@ class _LNURLWithdrawDialogState extends State with SingleTi } Future _withdraw(BuildContext context) async { - _log.v("Withdraw ${widget.amountSats} sats"); + _log.fine("Withdraw ${widget.amountSats} sats"); final texts = context.texts(); final accountBloc = context.read(); final description = widget.requestData.defaultDescription; try { - _log.v("LNURL withdraw of ${widget.amountSats} sats where " + _log.fine("LNURL withdraw of ${widget.amountSats} sats where " "min is ${widget.requestData.minWithdrawable} msats " "and max is ${widget.requestData.maxWithdrawable} msats."); final resp = await accountBloc.lnurlWithdraw( @@ -150,24 +150,24 @@ class _LNURLWithdrawDialogState extends State with SingleTi ); if (resp is sdk.LnUrlWithdrawResult_Ok) { final paymentHash = resp.data.invoice.paymentHash; - _log.v("LNURL withdraw success for $paymentHash"); + _log.fine("LNURL withdraw success for $paymentHash"); return const LNURLPageResult(protocol: LnUrlProtocol.Withdraw); } else if (resp is sdk.LnUrlWithdrawResult_ErrorStatus) { final reason = resp.data.reason; - _log.v("LNURL withdraw failed: $reason"); + _log.fine("LNURL withdraw failed: $reason"); return LNURLPageResult( protocol: LnUrlProtocol.Withdraw, error: reason, ); } else { - _log.w("Unknown response from lnurlWithdraw: $resp"); + _log.warning("Unknown response from lnurlWithdraw: $resp"); return LNURLPageResult( protocol: LnUrlProtocol.Withdraw, error: texts.lnurl_payment_page_unknown_error, ); } } catch (e) { - _log.w("Error withdrawing LNURL payment", ex: e); + _log.warning("Error withdrawing LNURL payment", e); return LNURLPageResult(protocol: LnUrlProtocol.Withdraw, error: e); } } @@ -177,7 +177,7 @@ class _LNURLWithdrawDialogState extends State with SingleTi return; } finishCalled = true; - _log.v("Finishing with result $result"); + _log.fine("Finishing with result $result"); widget.onFinish(result); } } diff --git a/lib/routes/lnurl/withdraw/lnurl_withdraw_handler.dart b/lib/routes/lnurl/withdraw/lnurl_withdraw_handler.dart index 22f7c470e..0a4131831 100644 --- a/lib/routes/lnurl/withdraw/lnurl_withdraw_handler.dart +++ b/lib/routes/lnurl/withdraw/lnurl_withdraw_handler.dart @@ -7,10 +7,10 @@ import 'package:c_breez/routes/create_invoice/widgets/successful_payment.dart'; import 'package:c_breez/routes/lnurl/widgets/lnurl_page_result.dart'; import 'package:c_breez/widgets/error_dialog.dart'; import 'package:c_breez/widgets/transparent_page_route.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; -final _log = FimberLog("handleLNURLWithdrawPageResult"); +final _log = Logger("handleLNURLWithdrawPageResult"); Future handleWithdrawRequest( BuildContext context, @@ -33,9 +33,9 @@ Future handleWithdrawRequest( } void handleLNURLWithdrawPageResult(BuildContext context, LNURLPageResult result) { - _log.v("handle $result"); + _log.fine("handle $result"); if (result.hasError) { - _log.v("Handle LNURL withdraw page result with error '${result.error}'"); + _log.fine("Handle LNURL withdraw page result with error '${result.error}'"); final texts = context.texts(); final themeData = Theme.of(context); promptError( @@ -48,7 +48,7 @@ void handleLNURLWithdrawPageResult(BuildContext context, LNURLPageResult result) ); throw result.error!; } else { - _log.v("Handle LNURL withdraw page result with success"); + _log.fine("Handle LNURL withdraw page result with success"); Navigator.of(context).push( TransparentPageRoute((ctx) => const SuccessfulPaymentRoute()), ); diff --git a/lib/routes/lsp/widgets/lsp_list_widget.dart b/lib/routes/lsp/widgets/lsp_list_widget.dart index 2ac9a84d1..bc7dab7ae 100644 --- a/lib/routes/lsp/widgets/lsp_list_widget.dart +++ b/lib/routes/lsp/widgets/lsp_list_widget.dart @@ -3,7 +3,7 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/lsp/lsp_bloc.dart'; import 'package:c_breez/routes/lsp/widgets/lsp_list.dart'; import 'package:c_breez/widgets/loader.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -24,7 +24,7 @@ class LspListWidget extends StatefulWidget { } class _LspListWidgetState extends State { - final _log = FimberLog("LspPage"); + final _log = Logger("LspPage"); Object? error; @@ -45,7 +45,7 @@ class _LspListWidgetState extends State { error = lspListSnapshot.error; if (error != null) { - _log.e("Error: $error"); + _log.severe("Error: $error"); widget.onError(error!); return const _LspErrorText(); } diff --git a/lib/routes/network/widget/mempool_settings_widget.dart b/lib/routes/network/widget/mempool_settings_widget.dart index 62bfbd135..aa8f9b77d 100644 --- a/lib/routes/network/widget/mempool_settings_widget.dart +++ b/lib/routes/network/widget/mempool_settings_widget.dart @@ -1,11 +1,11 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/network/network_settings_bloc.dart'; import 'package:c_breez/bloc/network/network_settings_state.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("MempoolSettingsWidget"); +final _log = Logger("MempoolSettingsWidget"); class MempoolSettingsWidget extends StatefulWidget { const MempoolSettingsWidget({ @@ -28,7 +28,7 @@ class _MempoolSettingsWidgetState extends State { return BlocBuilder( builder: (context, state) { - _log.v("Building: $state, userChanged: $_userChanged, saving: $_saving, errorOnSave: $_errorOnSave"); + _log.fine("Building: $state, userChanged: $_userChanged, saving: $_saving, errorOnSave: $_errorOnSave"); if (_mempoolUrlController.text.isEmpty && !_userChanged) { _mempoolUrlController.text = state.mempoolUrl; } diff --git a/lib/routes/payment_options/widget/actions_fee.dart b/lib/routes/payment_options/widget/actions_fee.dart index 0f70cb11e..8b8362070 100644 --- a/lib/routes/payment_options/widget/actions_fee.dart +++ b/lib/routes/payment_options/widget/actions_fee.dart @@ -2,11 +2,11 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/payment_options/payment_options_bloc.dart'; import 'package:c_breez/bloc/payment_options/payment_options_state.dart'; import 'package:c_breez/routes/payment_options/widget/save_dialog.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("ActionsFee"); +final _log = Logger("ActionsFee"); class ActionsFee extends StatelessWidget { const ActionsFee({ @@ -33,7 +33,7 @@ class ActionsFee extends StatelessWidget { texts.payment_options_fee_action_reset, ), onPressed: () { - _log.v("onPressed: reset"); + _log.fine("onPressed: reset"); context.read().resetFees(); }, ), @@ -47,7 +47,7 @@ class ActionsFee extends StatelessWidget { texts.payment_options_fee_action_save, ), onPressed: () { - _log.v("onPressed: save"); + _log.fine("onPressed: save"); if (state.overrideFeeEnabled) { showDialog( context: context, diff --git a/lib/routes/payment_options/widget/exempt_fee_widget.dart b/lib/routes/payment_options/widget/exempt_fee_widget.dart index 08eefc6ae..c8b40a18b 100644 --- a/lib/routes/payment_options/widget/exempt_fee_widget.dart +++ b/lib/routes/payment_options/widget/exempt_fee_widget.dart @@ -4,13 +4,13 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/payment_options/form_validator.dart'; import 'package:c_breez/bloc/payment_options/payment_options_bloc.dart'; import 'package:c_breez/bloc/payment_options/payment_options_state.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:rxdart/rxdart.dart'; -final _log = FimberLog("ExemptfeeMsatWidget"); +final _log = Logger("ExemptfeeMsatWidget"); class ExemptfeeMsatWidget extends StatefulWidget { const ExemptfeeMsatWidget({ @@ -60,12 +60,12 @@ class _ExemptfeeMsatState extends State { ), validator: exemptFeeValidator, onChanged: (value) { - _log.v("onChanged: $value"); + _log.fine("onChanged: $value"); int exemptFeeSat; try { exemptFeeSat = int.parse(value); } catch (_) { - _log.v("Failed to parse $value as int"); + _log.fine("Failed to parse $value as int"); return; } context.read().setExemptfeeMsat(exemptFeeSat * 1000); @@ -87,7 +87,7 @@ class _ExemptfeeMsatState extends State { final exemptFeeSat = (state.exemptFeeMsat ~/ 1000).toString(); if (_exemptFeeController.text != exemptFeeSat) { - _log.v("Setting exemptFee to $exemptFeeSat"); + _log.fine("Setting exemptFee to $exemptFeeSat"); setState(() { _exemptFeeController.text = exemptFeeSat; }); diff --git a/lib/routes/payment_options/widget/override_fee.dart b/lib/routes/payment_options/widget/override_fee.dart index 22f553517..a62a742c4 100644 --- a/lib/routes/payment_options/widget/override_fee.dart +++ b/lib/routes/payment_options/widget/override_fee.dart @@ -1,11 +1,11 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/payment_options/payment_options_bloc.dart'; import 'package:c_breez/bloc/payment_options/payment_options_state.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("OverrideFee"); +final _log = Logger("OverrideFee"); class OverrideFee extends StatelessWidget { const OverrideFee({ @@ -25,7 +25,7 @@ class OverrideFee extends StatelessWidget { controlAffinity: ListTileControlAffinity.leading, value: state.overrideFeeEnabled, onChanged: (value) { - _log.v("onChanged: $value"); + _log.fine("onChanged: $value"); if (value != null) { context.read().setOverrideFeeEnabled(value); } diff --git a/lib/routes/payment_options/widget/proportional_fee_widget.dart b/lib/routes/payment_options/widget/proportional_fee_widget.dart index 055233c56..6b589c877 100644 --- a/lib/routes/payment_options/widget/proportional_fee_widget.dart +++ b/lib/routes/payment_options/widget/proportional_fee_widget.dart @@ -4,14 +4,14 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/payment_options/form_validator.dart'; import 'package:c_breez/bloc/payment_options/payment_options_bloc.dart'; import 'package:c_breez/bloc/payment_options/payment_options_state.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:rxdart/rxdart.dart'; -final _log = FimberLog("ProportionalFeeWidget"); +final _log = Logger("ProportionalFeeWidget"); class ProportionalFeeWidget extends StatefulWidget { const ProportionalFeeWidget({ @@ -66,12 +66,12 @@ class _ProportionalFeeWidgetState extends State { ), validator: proportionalFeeValidator, onChanged: (value) { - _log.v("onChanged: $value"); + _log.fine("onChanged: $value"); double proportionalFee; try { proportionalFee = double.parse(value); } catch (_) { - _log.v("Failed to parse $value as double"); + _log.fine("Failed to parse $value as double"); return; } context.read().setProportionalFee(proportionalFee); @@ -92,7 +92,7 @@ class _ProportionalFeeWidgetState extends State { if (!state.saveEnabled) { final proportionalFee = state.proportionalFee.toStringAsFixed(2); if (_proportionalFeeController.text != proportionalFee) { - _log.v("Setting proportionalFee to $proportionalFee"); + _log.fine("Setting proportionalFee to $proportionalFee"); setState(() { _proportionalFeeController.text = proportionalFee; }); diff --git a/lib/routes/payment_options/widget/save_dialog.dart b/lib/routes/payment_options/widget/save_dialog.dart index 93ed24724..554784166 100644 --- a/lib/routes/payment_options/widget/save_dialog.dart +++ b/lib/routes/payment_options/widget/save_dialog.dart @@ -1,10 +1,10 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/payment_options/payment_options_bloc.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("SaveDialog"); +final _log = Logger("SaveDialog"); class SaveDialog extends StatelessWidget { const SaveDialog({ @@ -39,7 +39,7 @@ class SaveDialog extends StatelessWidget { style: themeData.primaryTextTheme.labelLarge, ), onPressed: () { - _log.v("onPressed: save"); + _log.fine("onPressed: save"); context.read().saveFees(); Navigator.pop(context); FocusManager.instance.primaryFocus?.unfocus(); diff --git a/lib/routes/qr_scan/widgets/qr_scan.dart b/lib/routes/qr_scan/widgets/qr_scan.dart index 61a2b041d..f6f83cc92 100644 --- a/lib/routes/qr_scan/widgets/qr_scan.dart +++ b/lib/routes/qr_scan/widgets/qr_scan.dart @@ -1,13 +1,13 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/routes/qr_scan/scan_overlay.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:image_picker/image_picker.dart'; import 'package:mobile_scanner/mobile_scanner.dart'; -final _log = FimberLog("QRScan"); +final _log = Logger("QRScan"); class QRScan extends StatefulWidget { @override @@ -45,21 +45,21 @@ class QRScanState extends State { onDetect: (capture) { final List barcodes = capture.barcodes; for (final barcode in barcodes) { - _log.i("Barcode detected: $barcode"); + _log.info("Barcode detected: $barcode"); if (popped) { - _log.v("Skipping, already popped"); + _log.fine("Skipping, already popped"); return; } if (!mounted) { - _log.v("Skipping, not mounted"); + _log.fine("Skipping, not mounted"); return; } final code = barcode.rawValue; if (code == null) { - _log.w("Failed to scan QR code."); + _log.warning("Failed to scan QR code."); } else { popped = true; - _log.i("Popping read QR code $code"); + _log.info("Popping read QR code $code"); Navigator.of(context).pop(code); } } @@ -123,24 +123,24 @@ class ImagePickerButton extends StatelessWidget { final picker = ImagePicker(); // ignore: body_might_complete_normally_catch_error final pickedFile = await picker.pickImage(source: ImageSource.gallery).catchError((err) { - _log.w("Failed to pick image", ex: err); + _log.warning("Failed to pick image", err); }); final filePath = pickedFile?.path; - _log.i("Picked image: $filePath"); + _log.info("Picked image: $filePath"); try { final found = filePath != null && await cameraController.analyzeImage(filePath); if (!found) { - _log.i("No QR code found in image"); + _log.info("No QR code found in image"); scaffoldMessenger.showSnackBar( SnackBar( content: Text(texts.qr_scan_gallery_failed), ), ); } else { - _log.i("QR code found in image"); + _log.info("QR code found in image"); } } catch (err) { - _log.w("Failed to analyze image", ex: err); + _log.warning("Failed to analyze image", err); } }, ); diff --git a/lib/routes/security/secured_page.dart b/lib/routes/security/secured_page.dart index a5884c448..2be21c181 100644 --- a/lib/routes/security/secured_page.dart +++ b/lib/routes/security/secured_page.dart @@ -2,11 +2,11 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/bloc/security/security_bloc.dart'; import 'package:c_breez/bloc/security/security_state.dart'; import 'package:c_breez/routes/security/widget/pin_code_widget.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("SecuredPage"); +final _log = Logger("SecuredPage"); class SecuredPage extends StatefulWidget { final Widget securedWidget; @@ -38,7 +38,7 @@ class _SecuredPageState extends State> { : BlocBuilder( key: ValueKey(DateTime.now().millisecondsSinceEpoch), builder: (context, state) { - _log.v("Building with: $state"); + _log.fine("Building with: $state"); if (state.pinStatus == PinStatus.enabled && !_allowed) { final texts = context.texts(); return Scaffold( @@ -48,25 +48,25 @@ class _SecuredPageState extends State> { body: PinCodeWidget( label: texts.lock_screen_enter_pin, testPinCodeFunction: (pin) async { - _log.v("Testing pin code"); + _log.fine("Testing pin code"); bool pinMatches = false; try { pinMatches = await context.read().testPin(pin); } catch (e) { - _log.e("Pin code test failed", ex: e); + _log.severe("Pin code test failed", e); return TestPinResult( false, errorMessage: texts.lock_screen_pin_match_exception, ); } if (pinMatches) { - _log.v("Pin matches"); + _log.fine("Pin matches"); setState(() { _allowed = true; }); return const TestPinResult(true); } else { - _log.v("Pin didn't match"); + _log.fine("Pin didn't match"); return TestPinResult( false, errorMessage: texts.lock_screen_pin_incorrect, diff --git a/lib/routes/subswap/swap/get_refund/widgets/refund_item_action.dart b/lib/routes/subswap/swap/get_refund/widgets/refund_item_action.dart index 13a8165f5..854b96bcb 100644 --- a/lib/routes/subswap/swap/get_refund/widgets/refund_item_action.dart +++ b/lib/routes/subswap/swap/get_refund/widgets/refund_item_action.dart @@ -4,10 +4,10 @@ import 'package:c_breez/routes/subswap/swap/get_refund/send_onchain.dart'; import 'package:c_breez/routes/subswap/swap/get_refund/wait_broadcast_dialog.dart'; import 'package:c_breez/widgets/route.dart'; import 'package:c_breez/widgets/single_button_bottom_bar.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; -final _log = FimberLog("RefundItemAction"); +final _log = Logger("RefundItemAction"); class RefundItemAction extends StatelessWidget { final SwapInfo swapInfo; @@ -68,7 +68,7 @@ class RefundItemAction extends StatelessWidget { String destAddress, int feeRate, ) { - _log.v("showWaitToBroadcastDialog destAddress: $destAddress feeRate: $feeRate"); + _log.fine("showWaitToBroadcastDialog destAddress: $destAddress feeRate: $feeRate"); final texts = context.texts(); return showDialog( diff --git a/lib/routes/subswap/swap/get_refund/widgets/send_onchain_form.dart b/lib/routes/subswap/swap/get_refund/widgets/send_onchain_form.dart index bd251b5f0..44c67d90c 100644 --- a/lib/routes/subswap/swap/get_refund/widgets/send_onchain_form.dart +++ b/lib/routes/subswap/swap/get_refund/widgets/send_onchain_form.dart @@ -7,12 +7,12 @@ import 'package:c_breez/theme/theme_provider.dart' as theme; import 'package:c_breez/utils/validator_holder.dart'; import 'package:c_breez/widgets/flushbar.dart'; import 'package:c_breez/widgets/keyboard_done_action.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("SendOnchainForm"); +final _log = Logger("SendOnchainForm"); class SendOnchainForm extends StatefulWidget { final int amount; @@ -114,7 +114,7 @@ class SendOnchainFormState extends State { ); }, validator: (address) { - _log.v('validator called for $address, lock status: ${validatorHolder.lock.locked}'); + _log.fine('validator called for $address, lock status: ${validatorHolder.lock.locked}'); if (validatorHolder.valid) { return null; } else { diff --git a/lib/routes/withdraw/reverse_swap/reverse_swap_page.dart b/lib/routes/withdraw/reverse_swap/reverse_swap_page.dart index f4a7dc477..29413aea6 100644 --- a/lib/routes/withdraw/reverse_swap/reverse_swap_page.dart +++ b/lib/routes/withdraw/reverse_swap/reverse_swap_page.dart @@ -18,11 +18,11 @@ import 'package:c_breez/widgets/back_button.dart' as back_button; import 'package:c_breez/widgets/loader.dart'; import 'package:c_breez/widgets/route.dart'; import 'package:c_breez/widgets/single_button_bottom_bar.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("ReverseSwapPage"); +final _log = Logger("ReverseSwapPage"); class ReverseSwapPage extends StatefulWidget { final BitcoinAddressData? btcAddressData; @@ -230,7 +230,7 @@ class _ReverseSwapPageState extends State { try { amount = bitcoinCurrency.parse(_amountController.text); } catch (e) { - _log.w("Failed to parse the input amount", ex: e); + _log.warning("Failed to parse the input amount", e); } return amount; } diff --git a/lib/routes/withdraw/sweep/sweep_page.dart b/lib/routes/withdraw/sweep/sweep_page.dart index df220e46d..762e4deab 100644 --- a/lib/routes/withdraw/sweep/sweep_page.dart +++ b/lib/routes/withdraw/sweep/sweep_page.dart @@ -12,11 +12,11 @@ import 'package:c_breez/widgets/back_button.dart' as back_button; import 'package:c_breez/widgets/route.dart'; import 'package:c_breez/widgets/single_button_bottom_bar.dart'; import 'package:c_breez/widgets/warning_box.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("SweepPage"); +final _log = Logger("SweepPage"); class SweepPage extends StatefulWidget { final int walletBalance; @@ -150,7 +150,7 @@ class _SweepPageState extends State { try { amount = bitcoinCurrency.parse(_amountController.text); } catch (e) { - _log.w("Failed to parse the input amount", ex: e); + _log.warning("Failed to parse the input amount", e); } return amount; } diff --git a/lib/routes/withdraw/widgets/bitcoin_address_text_form_field.dart b/lib/routes/withdraw/widgets/bitcoin_address_text_form_field.dart index 392690d03..306c7ec06 100644 --- a/lib/routes/withdraw/widgets/bitcoin_address_text_form_field.dart +++ b/lib/routes/withdraw/widgets/bitcoin_address_text_form_field.dart @@ -4,11 +4,11 @@ import 'package:c_breez/models/bitcoin_address_info.dart'; import 'package:c_breez/theme/theme_provider.dart' as theme; import 'package:c_breez/utils/validator_holder.dart'; import 'package:c_breez/widgets/flushbar.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("BitcoinAddressTextFormField"); +final _log = Logger("BitcoinAddressTextFormField"); class BitcoinAddressTextFormField extends TextFormField { BitcoinAddressTextFormField({ @@ -34,9 +34,9 @@ class BitcoinAddressTextFormField extends TextFormField { onPressed: () async { Navigator.pushNamed(context, "/qr_scan").then( (barcode) { - _log.v("Scanned string: '$barcode'"); + _log.fine("Scanned string: '$barcode'"); final address = BitcoinAddressInfo.fromScannedString(barcode).address; - _log.v("BitcoinAddressInfoFromScannedString: '$address'"); + _log.fine("BitcoinAddressInfoFromScannedString: '$address'"); if (address == null) return; if (address.isEmpty) { showFlushbar( @@ -55,7 +55,7 @@ class BitcoinAddressTextFormField extends TextFormField { style: theme.FieldTextStyle.textStyle, onChanged: (address) => _onAddressChanged(context, validatorHolder, address), validator: (address) { - _log.v("validator called for $address, $validatorHolder"); + _log.fine("validator called for $address, $validatorHolder"); if (validatorHolder.valid) { return null; } else { @@ -69,11 +69,11 @@ class BitcoinAddressTextFormField extends TextFormField { ValidatorHolder holder, String address, ) async { - _log.v("Address changed $address"); + _log.fine("Address changed $address"); await holder.lock.synchronized(() async { - _log.v("Calling validator for $address"); + _log.fine("Calling validator for $address"); holder.valid = await context.read().isValidBitcoinAddress(address); - _log.v("Address $address validation result $holder"); + _log.fine("Address $address validation result $holder"); }); } } diff --git a/lib/routes/withdraw/widgets/withdraw_funds_amount_text_form_field.dart b/lib/routes/withdraw/widgets/withdraw_funds_amount_text_form_field.dart index 9d0f5e606..75ad0dca0 100644 --- a/lib/routes/withdraw/widgets/withdraw_funds_amount_text_form_field.dart +++ b/lib/routes/withdraw/widgets/withdraw_funds_amount_text_form_field.dart @@ -5,11 +5,11 @@ import 'package:c_breez/models/currency.dart'; import 'package:c_breez/routes/withdraw/model/withdraw_funds_model.dart'; import 'package:c_breez/utils/payment_validator.dart'; import 'package:c_breez/widgets/amount_form_field/amount_form_field.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("WithdrawFundsAmountTextFormField"); +final _log = Logger("WithdrawFundsAmountTextFormField"); class WithdrawFundsAmountTextFormField extends AmountFormField { WithdrawFundsAmountTextFormField({ @@ -27,13 +27,13 @@ class WithdrawFundsAmountTextFormField extends AmountFormField { readOnly: policy.withdrawKind == WithdrawKind.unexpected_funds || withdrawMaxValue, bitcoinCurrency: bitcoinCurrency, validatorFn: (amount) { - _log.v("Validator called for $amount"); + _log.fine("Validator called for $amount"); return PaymentValidator( currency: bitcoinCurrency, texts: context.texts(), channelCreationPossible: context.read().state?.isChannelOpeningAvailable ?? false, validatePayment: (amount, outgoing, channelCreationPossible, {channelMinimumFee}) { - _log.v("Validating $amount $policy"); + _log.fine("Validating $amount $policy"); if (amount < policy.minValue) { throw PaymentBelowLimitError(policy.minValue); } diff --git a/lib/routes/withdraw/widgets/withdraw_funds_available_btc.dart b/lib/routes/withdraw/widgets/withdraw_funds_available_btc.dart index 9ae098ef5..6f3d15f74 100644 --- a/lib/routes/withdraw/widgets/withdraw_funds_available_btc.dart +++ b/lib/routes/withdraw/widgets/withdraw_funds_available_btc.dart @@ -4,11 +4,11 @@ import 'package:c_breez/bloc/account/account_state.dart'; import 'package:c_breez/bloc/currency/currency_bloc.dart'; import 'package:c_breez/bloc/currency/currency_state.dart'; import 'package:c_breez/theme/theme_provider.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = FimberLog("WithdrawFundsAvailableBtc"); +final _log = Logger("WithdrawFundsAvailableBtc"); class WithdrawFundsAvailableBtc extends StatelessWidget { const WithdrawFundsAvailableBtc(); @@ -33,7 +33,7 @@ class WithdrawFundsAvailableBtc extends StatelessWidget { padding: const EdgeInsets.only(left: 3.0), child: BlocBuilder( builder: (context, account) { - _log.v("Building with wallet balance: ${account.walletBalance} balance: ${account.balance}"); + _log.fine("Building with wallet balance: ${account.walletBalance} balance: ${account.balance}"); return BlocBuilder( builder: (context, currencyState) { return Text( diff --git a/lib/services/deep_links.dart b/lib/services/deep_links.dart index 69a50aa05..10d09ce0c 100644 --- a/lib/services/deep_links.dart +++ b/lib/services/deep_links.dart @@ -1,12 +1,12 @@ import 'dart:async'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:firebase_dynamic_links/firebase_dynamic_links.dart'; import 'package:rxdart/rxdart.dart'; class DeepLinksService { static const SESSION_SECRET = "sessionSecret"; - final _log = FimberLog("DeepLinksService"); + final _log = Logger("DeepLinksService"); final StreamController _linksNotificationsController = BehaviorSubject(); Stream get linksNotifications => _linksNotificationsController.stream; @@ -27,7 +27,7 @@ class DeepLinksService { _dynamicLinks!.onLink.listen((data) { publishLink(data); }).onError((err) { - _log.e("Failed to fetch dynamic link $err", ex: err); + _log.severe("Failed to fetch dynamic link $err", err); return Future.value(null); }); } diff --git a/lib/services/device.dart b/lib/services/device.dart index 596b235ab..9c702ecc0 100644 --- a/lib/services/device.dart +++ b/lib/services/device.dart @@ -1,14 +1,14 @@ import 'dart:async'; import 'package:clipboard_watcher/clipboard_watcher.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/services.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:rxdart/rxdart.dart'; import 'package:share_plus/share_plus.dart'; import 'package:shared_preferences/shared_preferences.dart'; -final _log = FimberLog("Device"); +final _log = Logger("Device"); class Device extends ClipboardListener { final _clipboardController = BehaviorSubject(); @@ -20,12 +20,12 @@ class Device extends ClipboardListener { String? _lastFromAppClip; Device() { - _log.v("Initing Device"); + _log.fine("Initing Device"); var sharedPreferences = SharedPreferences.getInstance(); sharedPreferences.then((preferences) { _lastFromAppClip = preferences.getString(LAST_FROM_APP_CLIPPING_PREFERENCES_KEY); _clipboardController.add(preferences.getString(LAST_CLIPPING_PREFERENCES_KEY) ?? ""); - _log.v("Last clipping: $_lastFromAppClip"); + _log.fine("Last clipping: $_lastFromAppClip"); fetchClipboard(preferences); }); clipboardWatcher.addListener(this); @@ -33,7 +33,7 @@ class Device extends ClipboardListener { } Future setClipboardText(String text) async { - _log.v("Setting clipboard text: $text"); + _log.fine("Setting clipboard text: $text"); _lastFromAppClip = text; final prefs = await SharedPreferences.getInstance(); prefs.setString(LAST_FROM_APP_CLIPPING_PREFERENCES_KEY, text); @@ -41,15 +41,15 @@ class Device extends ClipboardListener { } Future shareText(String text) { - _log.v("Sharing text: $text"); + _log.fine("Sharing text: $text"); return Share.share(text); } void fetchClipboard(SharedPreferences preferences) { - _log.v("Fetching clipboard"); + _log.fine("Fetching clipboard"); Clipboard.getData("text/plain").then((clipboardData) { final text = clipboardData?.text; - _log.v("Clipboard text: $text"); + _log.fine("Clipboard text: $text"); if (text != null) { _clipboardController.add(text); preferences.setString(LAST_CLIPPING_PREFERENCES_KEY, text); @@ -64,7 +64,7 @@ class Device extends ClipboardListener { @override void onClipboardChanged() { - _log.v("Clipboard changed"); + _log.fine("Clipboard changed"); SharedPreferences.getInstance().then((preferences) { fetchClipboard(preferences); }); diff --git a/lib/services/lightning_links.dart b/lib/services/lightning_links.dart index 7aa55bde2..868b461fb 100644 --- a/lib/services/lightning_links.dart +++ b/lib/services/lightning_links.dart @@ -1,11 +1,11 @@ import 'dart:async'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:rxdart/rxdart.dart'; import 'package:uni_links/uni_links.dart'; class LightningLinksService { - final _log = FimberLog("LightningLinksService"); + final _log = Logger("LightningLinksService"); final StreamController _linksNotificationsController = BehaviorSubject(); Stream get linksNotifications => _linksNotificationsController.stream; @@ -15,7 +15,7 @@ class LightningLinksService { getInitialLink().asStream(), linkStream, ]).where(_canHandle).listen((l) { - _log.i("Got lightning link: $l"); + _log.info("Got lightning link: $l"); if (l!.startsWith("breez:")) { l = l.substring(6); } diff --git a/lib/services/notifications.dart b/lib/services/notifications.dart index 789d8b44b..f77291595 100644 --- a/lib/services/notifications.dart +++ b/lib/services/notifications.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'dart:convert'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:rxdart/rxdart.dart'; @@ -11,7 +11,7 @@ abstract class Notifications { } class FirebaseNotifications implements Notifications { - final _log = FimberLog("FirebaseNotifications"); + final _log = Logger("FirebaseNotifications"); FirebaseMessaging get _firebaseMessaging { return FirebaseMessaging.instance; @@ -28,7 +28,7 @@ class FirebaseNotifications implements Notifications { } Future _onMessage(RemoteMessage message) { - _log.i("_onMessage = ${message.data}"); + _log.info("_onMessage = ${message.data}"); var data = message.data["data"] ?? message.data["aps"] ?? message.data; if (data != null) { if (data is String) data = json.decode(data); @@ -38,7 +38,7 @@ class FirebaseNotifications implements Notifications { } Future _onResume(RemoteMessage message) { - _log.i("_onResume = ${message.data}"); + _log.info("_onResume = ${message.data}"); var data = message.data["data"] ?? message.data; if (data != null) { if (data is String) data = json.decode(data); @@ -49,14 +49,14 @@ class FirebaseNotifications implements Notifications { @override Future getToken() async { - _log.v("getToken"); + _log.fine("getToken"); NotificationSettings firebaseNotificationSettings = await _firebaseMessaging.requestPermission(sound: true, badge: true, alert: true); if (firebaseNotificationSettings.authorizationStatus == AuthorizationStatus.authorized) { - _log.v("Authorized to get token"); + _log.fine("Authorized to get token"); return _firebaseMessaging.getToken(); } else { - _log.w("Unauthorized to get token"); + _log.warning("Unauthorized to get token"); return null; } } diff --git a/lib/user_app.dart b/lib/user_app.dart index 50fecb4c3..85b4e8138 100644 --- a/lib/user_app.dart +++ b/lib/user_app.dart @@ -35,7 +35,7 @@ import 'package:c_breez/theme/breez_dark_theme.dart'; import 'package:c_breez/theme/breez_light_theme.dart'; import 'package:c_breez/widgets/route.dart'; import 'package:c_breez/widgets/transparent_page_route.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -43,7 +43,7 @@ import 'package:theme_provider/theme_provider.dart'; const String THEME_ID_PREFERENCE_KEY = "themeID"; -final _log = FimberLog("UserApp"); +final _log = Logger("UserApp"); class UserApp extends StatelessWidget { final GlobalKey _appKey = GlobalKey(); @@ -101,7 +101,7 @@ class UserApp extends StatelessWidget { }, initialRoute: securityState.pinStatus == PinStatus.enabled ? "lockscreen" : "splash", onGenerateRoute: (RouteSettings settings) { - _log.v("New route: $settings"); + _log.fine("New route: $settings"); switch (settings.name) { case '/intro': return FadeInRoute( @@ -137,7 +137,7 @@ class UserApp extends StatelessWidget { initialRoute: "/", key: _homeNavigatorKey, onGenerateRoute: (RouteSettings settings) { - _log.v("New inner route: $settings"); + _log.fine("New inner route: $settings"); switch (settings.name) { case '/': return FadeInRoute( diff --git a/lib/utils/exceptions.dart b/lib/utils/exceptions.dart index dacf7045b..fe0ab5016 100644 --- a/lib/utils/exceptions.dart +++ b/lib/utils/exceptions.dart @@ -1,15 +1,15 @@ import 'package:breez_translations/generated/breez_translations.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import "package:flutter_rust_bridge/flutter_rust_bridge.dart"; -final _log = FimberLog("exceptions"); +final _log = Logger("exceptions"); String extractExceptionMessage( Object exception, BreezTranslations texts, { String? defaultErrorMsg, }) { - _log.v("extractExceptionMessage: $exception"); + _log.fine("extractExceptionMessage: $exception"); if (exception is FfiException) { if (exception.message.isNotEmpty) { var message = exception.message.replaceAll("\n", " ").trim(); @@ -22,7 +22,7 @@ String extractExceptionMessage( } String? _extractInnerErrorMessage(String content) { - _log.v("extractInnerErrorMessage: $content"); + _log.fine("extractInnerErrorMessage: $content"); final innerMessageRegex = RegExp(r'((?<=message: \\")(.*)(?=.*\\"))'); final messageRegex = RegExp(r'((?<=message: ")(.*)(?=.*"))'); final causedByRegex = RegExp(r'((?<=Caused by: )(.*)(?=.*))'); @@ -37,7 +37,7 @@ String _localizedExceptionMessage( BreezTranslations texts, String originalMessage, ) { - _log.v("localizedExceptionMessage: $originalMessage"); + _log.fine("localizedExceptionMessage: $originalMessage"); final messageToLower = originalMessage.toLowerCase(); if (messageToLower == "transport error") { return texts.generic_network_error; diff --git a/lib/utils/external_browser.dart b/lib/utils/external_browser.dart index 9a56634ea..07ce15bc8 100644 --- a/lib/utils/external_browser.dart +++ b/lib/utils/external_browser.dart @@ -1,11 +1,11 @@ import 'package:breez_translations/breez_translations_locales.dart'; import 'package:c_breez/widgets/loader.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:url_launcher/url_launcher_string.dart'; -final _log = FimberLog("ExternalBrowser"); +final _log = Logger("ExternalBrowser"); Future launchLinkOnExternalBrowser( BuildContext context, { @@ -40,7 +40,7 @@ Future launchLinkOnExternalBrowser( throw Exception(texts.link_launcher_failed_to_launch(linkAddress)); } } catch (error) { - _log.w(error.toString(), ex: error); + _log.warning(error.toString(), error); rethrow; } finally { navigator.removeRoute(loaderRoute); diff --git a/lib/utils/payment_validator.dart b/lib/utils/payment_validator.dart index 0741e7a1f..48f644243 100644 --- a/lib/utils/payment_validator.dart +++ b/lib/utils/payment_validator.dart @@ -2,9 +2,9 @@ import 'package:breez_translations/generated/breez_translations.dart'; import 'package:c_breez/bloc/account/payment_error.dart'; import 'package:c_breez/models/currency.dart'; import 'package:c_breez/utils/exceptions.dart'; -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; -final _log = FimberLog("PaymentValidator"); +final _log = Logger("PaymentValidator"); class PaymentValidator { final BitcoinCurrency currency; @@ -35,21 +35,21 @@ class PaymentValidator { } String? _validate(int amount, bool outgoing) { - _log.v("Validating for $amount and $outgoing"); + _log.fine("Validating for $amount and $outgoing"); try { validatePayment(amount, outgoing, channelCreationPossible, channelMinimumFee: channelMinimumFee); } on PaymentExceededLimitError catch (e) { - _log.v("Got PaymentExceededLimitError", ex: e); + _log.fine("Got PaymentExceededLimitError", e); return texts.invoice_payment_validator_error_payment_exceeded_limit( currency.format(e.limitSat), ); } on PaymentBelowLimitError catch (e) { - _log.v("Got PaymentBelowLimitError", ex: e); + _log.fine("Got PaymentBelowLimitError", e); return texts.invoice_payment_validator_error_payment_below_invoice_limit( currency.format(e.limitSat), ); } on PaymentBelowReserveError catch (e) { - _log.v("Got PaymentBelowReserveError", ex: e); + _log.fine("Got PaymentBelowReserveError", e); return texts.invoice_payment_validator_error_payment_below_limit( currency.format(e.reserveAmount), ); @@ -58,7 +58,7 @@ class PaymentValidator { } on InsufficientLocalBalanceError { return texts.invoice_payment_validator_error_insufficient_local_balance; } on PaymentBelowSetupFeesError catch (e) { - _log.v("Got PaymentBelowSetupFeesError", ex: e); + _log.fine("Got PaymentBelowSetupFeesError", e); return texts.invoice_payment_validator_error_payment_below_setup_fees_error( currency.format(e.setupFees), ); @@ -67,7 +67,7 @@ class PaymentValidator { } on NoChannelCreationZeroLiqudityError { return texts.lsp_error_cannot_open_channel; } catch (e) { - _log.v("Got Generic error", ex: e); + _log.fine("Got Generic error", e); return texts.invoice_payment_validator_error_unknown( extractExceptionMessage(e, texts), ); diff --git a/lib/utils/preferences.dart b/lib/utils/preferences.dart index dc5f05cf8..597933c59 100644 --- a/lib/utils/preferences.dart +++ b/lib/utils/preferences.dart @@ -1,4 +1,4 @@ -import 'package:fimber/fimber.dart'; +import 'package:logging/logging.dart'; import 'package:shared_preferences/shared_preferences.dart'; const kDefaultOverrideFee = false; @@ -10,7 +10,7 @@ const _kPaymentOptionOverrideFee = "payment_options_override_fee"; const _kPaymentOptionProportionalFee = "payment_options_proportional_fee"; const _kPaymentOptionExemptFee = "payment_options_exempt_fee"; -final _log = FimberLog("preferences"); +final _log = Logger("preferences"); class Preferences { Future getMempoolSpaceUrl() async { @@ -19,7 +19,7 @@ class Preferences { } Future setMempoolSpaceUrl(String url) async { - _log.d("set mempool space url: $url"); + _log.fine("set mempool space url: $url"); final prefs = await SharedPreferences.getInstance(); await prefs.setString(_mempoolSpaceUrlKey, url); } @@ -35,7 +35,7 @@ class Preferences { } Future setPaymentOptionsOverrideFeeEnabled(bool enabled) async { - _log.d("set payment options override fee enabled: $enabled"); + _log.fine("set payment options override fee enabled: $enabled"); final prefs = await SharedPreferences.getInstance(); await prefs.setBool(_kPaymentOptionOverrideFee, enabled); } @@ -46,7 +46,7 @@ class Preferences { } Future setPaymentOptionsProportionalFee(double fee) async { - _log.d("set payment options proportional fee: $fee"); + _log.fine("set payment options proportional fee: $fee"); final prefs = await SharedPreferences.getInstance(); await prefs.setDouble(_kPaymentOptionProportionalFee, fee); } @@ -57,7 +57,7 @@ class Preferences { } Future setPaymentOptionsExemptFee(int exemptfeeMsat) async { - _log.d("set payment options exempt fee : $exemptfeeMsat"); + _log.fine("set payment options exempt fee : $exemptfeeMsat"); final prefs = await SharedPreferences.getInstance(); await prefs.setInt(_kPaymentOptionExemptFee, exemptfeeMsat); } diff --git a/pubspec.lock b/pubspec.lock index 1d1432e18..dfc303176 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -95,7 +95,7 @@ packages: path: "../breez-sdk/libs/sdk-flutter" relative: true source: path - version: "0.2.3" + version: "0.2.5" breez_translations: dependency: "direct main" description: @@ -401,22 +401,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.9.3+1" - fimber: - dependency: "direct main" - description: - name: fimber - sha256: "42fcfa33acd43556c1e7ebfc12c2b03893418bc04a07931368c3573e228af2f0" - url: "https://pub.dev" - source: hosted - version: "0.7.0" - fimber_io: - dependency: "direct main" - description: - name: fimber_io - sha256: "6b80d4628c717c03e3e8a3a801b2d67b71f0ff2cfd9754b67943576313dbac57" - url: "https://pub.dev" - source: hosted - version: "0.7.0" firebase_core: dependency: "direct main" description: @@ -983,7 +967,7 @@ packages: source: hosted version: "1.0.8" logging: - dependency: transitive + dependency: "direct main" description: name: logging sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" diff --git a/pubspec.yaml b/pubspec.yaml index 7fcd7820e..56ccc7989 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -32,8 +32,6 @@ dependencies: email_validator: ^2.1.17 extended_image: <8.0.0 # Requires Flutter 3.10 ffi: <2.1.0 # Requires Flutter 3.10 - fimber: ^0.7.0 - fimber_io: ^0.7.0 # Doesn't support: Linux Windows firebase_core: ^2.15.0 # Doesn't support: Linux Mac Windows @@ -68,6 +66,7 @@ dependencies: local_auth: ^2.1.6 local_auth_android: <1.0.32 # Requires Flutter 3.10 local_auth_ios: ^1.1.3 + logging: ^1.2.0 mockito: <5.4.1 # flutter_test requirement # Doesn't support: Linux Windows mobile_scanner: <3.3.0 # Kotlin requirement diff --git a/test/unit_logger.dart b/test/unit_logger.dart index cb7da0eae..7db30a8d4 100644 --- a/test/unit_logger.dart +++ b/test/unit_logger.dart @@ -1,24 +1,12 @@ -import 'package:fimber/fimber.dart'; import 'package:flutter/foundation.dart'; +import 'package:logging/logging.dart'; -void setUpLogger() => Fimber.plantTree(UnitLogTree()); +void setUpLogger() { + Logger.root.level = Level.ALL; -class UnitLogTree extends LogTree { - @override - List getLevels() => ["V", "D", "I", "W", "E"]; - - @override - void log( - String level, - String message, { - String? tag, - Object? ex, - StackTrace? stacktrace, - }) { - if (kDebugMode) { - print("$tag [$level] $message"); - if (ex != null) print(ex); - if (stacktrace != null) print(stacktrace); - } + if (kDebugMode) { + Logger.root.onRecord.listen((record) { + print("[${record.loggerName}] {${record.level.name}} (${record.time}) : ${record.message}"); + }); } } From 89bde3af542fe39ca92824f4328d23b59c3ad3b8 Mon Sep 17 00:00:00 2001 From: Ademar Alves de Oliveira Date: Thu, 5 Oct 2023 17:39:08 -0300 Subject: [PATCH 2/4] Fix dart analyzer --- lib/logger.dart | 32 +++++++++++++++++-- lib/main.dart | 5 ++- lib/routes/lnurl/auth/lnurl_auth_handler.dart | 2 +- lib/routes/lnurl/lnurl_invoice_delegate.dart | 2 +- .../lnurl/payment/lnurl_payment_handler.dart | 2 +- .../withdraw/lnurl_withdraw_handler.dart | 2 +- lib/utils/exceptions.dart | 2 +- lib/utils/preferences.dart | 2 +- test/unit_logger.dart | 5 ++- 9 files changed, 44 insertions(+), 10 deletions(-) diff --git a/lib/logger.dart b/lib/logger.dart index 40bf47add..20bd33b8c 100644 --- a/lib/logger.dart +++ b/lib/logger.dart @@ -3,12 +3,14 @@ library breez.logger; import 'dart:io'; import 'package:archive/archive_io.dart'; +import 'package:breez_sdk/breez_sdk.dart'; import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; import 'package:path_provider/path_provider.dart'; import 'package:share_plus/share_plus.dart'; -final _log = Logger("logger"); +final _log = Logger("Logger"); +final _sdkLog = Logger("BreezSdk"); void shareLog() async { final appDir = await getApplicationDocumentsDirectory(); @@ -27,7 +29,10 @@ class BreezLogger { if (kDebugMode) { Logger.root.onRecord.listen((record) { - print(_recordToString(record)); + // Dart analyzer doesn't understand that here we are in debug mode so we have to use kDebugMode again + if (kDebugMode) { + print(_recordToString(record)); + } }); } @@ -57,6 +62,29 @@ class BreezLogger { }; } + /// Log entries according to their severity + void registerBreezSdkLog(BreezSDK sdk) { + sdk.logStream.listen((log) { + switch (log.level) { + case "ERROR": + _sdkLog.severe(log.line); + break; + case "WARN": + _sdkLog.warning(log.line); + break; + case "INFO": + _sdkLog.info(log.line); + break; + case "DEBUG": + _sdkLog.config(log.line); + break; + default: + _sdkLog.fine(log.line); + break; + } + }); + } + String _recordToString(LogRecord record) => "[${record.loggerName}] {${record.level.name}} (${record.time}) : ${record.message}"; diff --git a/lib/main.dart b/lib/main.dart index 101ddee80..332df3811 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -44,7 +44,7 @@ void main() async { // runZonedGuarded wrapper is required to log Dart errors. runZonedGuarded(() async { WidgetsFlutterBinding.ensureInitialized(); - BreezLogger(); + final logger = BreezLogger(); SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown], ); @@ -52,8 +52,11 @@ void main() async { BreezDateUtils.setupLocales(); await Firebase.initializeApp(); final injector = ServiceInjector(); + final breezLib = injector.breezSDK; breezLib.initialize(); + logger.registerBreezSdkLog(breezLib); + FirebaseMessaging.onBackgroundMessage(_onBackgroundMessage); final appDir = await getApplicationDocumentsDirectory(); final config = await cfg.Config.instance(); diff --git a/lib/routes/lnurl/auth/lnurl_auth_handler.dart b/lib/routes/lnurl/auth/lnurl_auth_handler.dart index f6f34bb8d..4ebc60717 100644 --- a/lib/routes/lnurl/auth/lnurl_auth_handler.dart +++ b/lib/routes/lnurl/auth/lnurl_auth_handler.dart @@ -9,7 +9,7 @@ import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = Logger("handleLNURLAuthRequest"); +final _log = Logger("HandleLNURLAuthRequest"); Future handleAuthRequest( BuildContext context, diff --git a/lib/routes/lnurl/lnurl_invoice_delegate.dart b/lib/routes/lnurl/lnurl_invoice_delegate.dart index a914e56b3..f46e0f92e 100644 --- a/lib/routes/lnurl/lnurl_invoice_delegate.dart +++ b/lib/routes/lnurl/lnurl_invoice_delegate.dart @@ -10,7 +10,7 @@ import 'package:flutter/material.dart'; import 'widgets/lnurl_page_result.dart'; -final _log = Logger("handleLNURL"); +final _log = Logger("HandleLNURL"); Future handleLNURL( BuildContext context, diff --git a/lib/routes/lnurl/payment/lnurl_payment_handler.dart b/lib/routes/lnurl/payment/lnurl_payment_handler.dart index a2e11e65d..92665fd6b 100644 --- a/lib/routes/lnurl/payment/lnurl_payment_handler.dart +++ b/lib/routes/lnurl/payment/lnurl_payment_handler.dart @@ -11,7 +11,7 @@ import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -final _log = Logger("handleLNURLPayRequest"); +final _log = Logger("HandleLNURLPayRequest"); Future handlePayRequest( BuildContext context, diff --git a/lib/routes/lnurl/withdraw/lnurl_withdraw_handler.dart b/lib/routes/lnurl/withdraw/lnurl_withdraw_handler.dart index 0a4131831..8593b02db 100644 --- a/lib/routes/lnurl/withdraw/lnurl_withdraw_handler.dart +++ b/lib/routes/lnurl/withdraw/lnurl_withdraw_handler.dart @@ -10,7 +10,7 @@ import 'package:c_breez/widgets/transparent_page_route.dart'; import 'package:logging/logging.dart'; import 'package:flutter/material.dart'; -final _log = Logger("handleLNURLWithdrawPageResult"); +final _log = Logger("HandleLNURLWithdrawPageResult"); Future handleWithdrawRequest( BuildContext context, diff --git a/lib/utils/exceptions.dart b/lib/utils/exceptions.dart index fe0ab5016..8bbfa7f05 100644 --- a/lib/utils/exceptions.dart +++ b/lib/utils/exceptions.dart @@ -2,7 +2,7 @@ import 'package:breez_translations/generated/breez_translations.dart'; import 'package:logging/logging.dart'; import "package:flutter_rust_bridge/flutter_rust_bridge.dart"; -final _log = Logger("exceptions"); +final _log = Logger("Exceptions"); String extractExceptionMessage( Object exception, diff --git a/lib/utils/preferences.dart b/lib/utils/preferences.dart index 597933c59..3a6c1ab6e 100644 --- a/lib/utils/preferences.dart +++ b/lib/utils/preferences.dart @@ -10,7 +10,7 @@ const _kPaymentOptionOverrideFee = "payment_options_override_fee"; const _kPaymentOptionProportionalFee = "payment_options_proportional_fee"; const _kPaymentOptionExemptFee = "payment_options_exempt_fee"; -final _log = Logger("preferences"); +final _log = Logger("Preferences"); class Preferences { Future getMempoolSpaceUrl() async { diff --git a/test/unit_logger.dart b/test/unit_logger.dart index 7db30a8d4..319d7ae8e 100644 --- a/test/unit_logger.dart +++ b/test/unit_logger.dart @@ -6,7 +6,10 @@ void setUpLogger() { if (kDebugMode) { Logger.root.onRecord.listen((record) { - print("[${record.loggerName}] {${record.level.name}} (${record.time}) : ${record.message}"); + // Dart analyzer doesn't understand that here we are in debug mode so we have to use kDebugMode again + if (kDebugMode) { + print("[${record.loggerName}] {${record.level.name}} (${record.time}) : ${record.message}"); + } }); } } From b1705337c3a7dadfa911433bd563e9ddb3138ad1 Mon Sep 17 00:00:00 2001 From: Ademar Alves de Oliveira Date: Fri, 6 Oct 2023 09:07:09 -0300 Subject: [PATCH 3/4] Uses utc time --- lib/logger.dart | 4 +++- pubspec.lock | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/logger.dart b/lib/logger.dart index 20bd33b8c..4ad413d55 100644 --- a/lib/logger.dart +++ b/lib/logger.dart @@ -86,7 +86,9 @@ class BreezLogger { } String _recordToString(LogRecord record) => - "[${record.loggerName}] {${record.level.name}} (${record.time}) : ${record.message}"; + "[${record.loggerName}] {${record.level.name}} (${_formatTime(record.time)}) : ${record.message}"; + + String _formatTime(DateTime time) => time.toUtc().toIso8601String(); String _logDir(Directory appDir) => "${appDir.path}/logs/"; diff --git a/pubspec.lock b/pubspec.lock index dfc303176..dd389e7b5 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -401,6 +401,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.9.3+1" + fimber: + dependency: transitive + description: + name: fimber + sha256: "42fcfa33acd43556c1e7ebfc12c2b03893418bc04a07931368c3573e228af2f0" + url: "https://pub.dev" + source: hosted + version: "0.7.0" firebase_core: dependency: "direct main" description: From 0b3ea77e01e9961ca04eb02c8ebe5f37a86c384c Mon Sep 17 00:00:00 2001 From: Ademar Alves de Oliveira Date: Mon, 9 Oct 2023 09:14:39 -0300 Subject: [PATCH 4/4] Dart format --- lib/routes/network/widget/mempool_settings_widget.dart | 3 ++- lib/routes/withdraw/widgets/withdraw_funds_available_btc.dart | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/routes/network/widget/mempool_settings_widget.dart b/lib/routes/network/widget/mempool_settings_widget.dart index aa8f9b77d..dde9d05fe 100644 --- a/lib/routes/network/widget/mempool_settings_widget.dart +++ b/lib/routes/network/widget/mempool_settings_widget.dart @@ -28,7 +28,8 @@ class _MempoolSettingsWidgetState extends State { return BlocBuilder( builder: (context, state) { - _log.fine("Building: $state, userChanged: $_userChanged, saving: $_saving, errorOnSave: $_errorOnSave"); + _log.fine( + "Building: $state, userChanged: $_userChanged, saving: $_saving, errorOnSave: $_errorOnSave"); if (_mempoolUrlController.text.isEmpty && !_userChanged) { _mempoolUrlController.text = state.mempoolUrl; } diff --git a/lib/routes/withdraw/widgets/withdraw_funds_available_btc.dart b/lib/routes/withdraw/widgets/withdraw_funds_available_btc.dart index 6f3d15f74..a3adb3ad7 100644 --- a/lib/routes/withdraw/widgets/withdraw_funds_available_btc.dart +++ b/lib/routes/withdraw/widgets/withdraw_funds_available_btc.dart @@ -33,7 +33,8 @@ class WithdrawFundsAvailableBtc extends StatelessWidget { padding: const EdgeInsets.only(left: 3.0), child: BlocBuilder( builder: (context, account) { - _log.fine("Building with wallet balance: ${account.walletBalance} balance: ${account.balance}"); + _log.fine( + "Building with wallet balance: ${account.walletBalance} balance: ${account.balance}"); return BlocBuilder( builder: (context, currencyState) { return Text(