refactor: more logs

This commit is contained in:
cogwheel0
2025-09-25 23:22:48 +05:30
parent 9210b2155a
commit 3124bccfeb
20 changed files with 937 additions and 846 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -5,11 +5,6 @@ import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/debug_logger.dart';
void debugPrint(String? message, {int? wrapWidth}) {
if (message == null) return;
DebugLogger.fromLegacy(message, scope: 'attachments/queue');
}
/// Status of a queued attachment upload
enum QueuedAttachmentStatus { pending, uploading, completed, failed, cancelled }
@@ -144,8 +139,9 @@ class AttachmentUploadQueue {
_prefs ??= await SharedPreferences.getInstance();
await _load();
_startPeriodicProcessing();
debugPrint(
'DEBUG: AttachmentUploadQueue initialized with ${_queue.length} items',
DebugLogger.log(
'AttachmentUploadQueue initialized with ${_queue.length} items',
scope: 'attachments/queue',
);
}
@@ -223,8 +219,9 @@ class AttachmentUploadQueue {
await _save();
_notify();
debugPrint(
'DEBUG: Attachment ${item.id} uploaded successfully (fileId=$fileId)',
DebugLogger.log(
'Attachment ${item.id} uploaded successfully (fileId=$fileId)',
scope: 'attachments/queue',
);
} catch (e) {
final retries = item.retryCount + 1;
@@ -239,8 +236,9 @@ class AttachmentUploadQueue {
);
await _save();
_notify();
debugPrint(
DebugLogger.log(
'WARNING: Attachment ${item.id} failed after $_maxRetries attempts',
scope: 'attachments/queue',
);
return;
}
@@ -257,8 +255,9 @@ class AttachmentUploadQueue {
);
await _save();
_notify();
debugPrint(
'DEBUG: Scheduled retry for attachment ${item.id} in ${delay.inSeconds}s',
DebugLogger.log(
'Scheduled retry for attachment ${item.id} in ${delay.inSeconds}s',
scope: 'attachments/queue',
);
}
}

View File

@@ -6,11 +6,6 @@ import '../models/server_config.dart';
import '../models/conversation.dart';
import '../utils/debug_logger.dart';
void debugPrint(String? message, {int? wrapWidth}) {
if (message == null) return;
DebugLogger.fromLegacy(message, scope: 'storage/optimized');
}
/// Optimized storage service with single secure storage implementation
/// Eliminates dual storage overhead and improves performance
class OptimizedStorageService {
@@ -46,9 +41,15 @@ class OptimizedStorageService {
await _secureCredentialStorage.saveAuthToken(token);
_cache[_authTokenKey] = token;
_cacheTimestamps[_authTokenKey] = DateTime.now();
debugPrint('DEBUG: Auth token saved and cached');
DebugLogger.log(
'Auth token saved and cached',
scope: 'storage/optimized',
);
} catch (e) {
debugPrint('ERROR: Failed to save auth token: $e');
DebugLogger.log(
'Failed to save auth token: $e',
scope: 'storage/optimized',
);
rethrow;
}
}
@@ -58,7 +59,7 @@ class OptimizedStorageService {
if (_isCacheValid(_authTokenKey)) {
final cachedToken = _cache[_authTokenKey] as String?;
if (cachedToken != null) {
debugPrint('DEBUG: Using cached auth token');
DebugLogger.log('Using cached auth token', scope: 'storage/optimized');
return cachedToken;
}
}
@@ -71,7 +72,10 @@ class OptimizedStorageService {
}
return token;
} catch (e) {
debugPrint('ERROR: Failed to retrieve auth token: $e');
DebugLogger.log(
'Failed to retrieve auth token: $e',
scope: 'storage/optimized',
);
return null;
}
}
@@ -81,9 +85,15 @@ class OptimizedStorageService {
await _secureCredentialStorage.deleteAuthToken();
_cache.remove(_authTokenKey);
_cacheTimestamps.remove(_authTokenKey);
debugPrint('DEBUG: Auth token deleted and cache cleared');
DebugLogger.log(
'Auth token deleted and cache cleared',
scope: 'storage/optimized',
);
} catch (e) {
debugPrint('ERROR: Failed to delete auth token: $e');
DebugLogger.log(
'Failed to delete auth token: $e',
scope: 'storage/optimized',
);
}
}
@@ -104,9 +114,15 @@ class OptimizedStorageService {
_cache['has_credentials'] = true;
_cacheTimestamps['has_credentials'] = DateTime.now();
debugPrint('DEBUG: Credentials saved via optimized storage');
DebugLogger.log(
'Credentials saved via optimized storage',
scope: 'storage/optimized',
);
} catch (e) {
debugPrint('ERROR: Failed to save credentials: $e');
DebugLogger.log(
'Failed to save credentials: $e',
scope: 'storage/optimized',
);
rethrow;
}
}
@@ -122,7 +138,10 @@ class OptimizedStorageService {
return credentials;
} catch (e) {
debugPrint('ERROR: Failed to retrieve credentials: $e');
DebugLogger.log(
'Failed to retrieve credentials: $e',
scope: 'storage/optimized',
);
return null;
}
}
@@ -132,9 +151,15 @@ class OptimizedStorageService {
await _secureCredentialStorage.deleteSavedCredentials();
_cache.remove('has_credentials');
_cacheTimestamps.remove('has_credentials');
debugPrint('DEBUG: Credentials deleted via optimized storage');
DebugLogger.log(
'Credentials deleted via optimized storage',
scope: 'storage/optimized',
);
} catch (e) {
debugPrint('ERROR: Failed to delete credentials: $e');
DebugLogger.log(
'Failed to delete credentials: $e',
scope: 'storage/optimized',
);
}
}
@@ -167,9 +192,15 @@ class OptimizedStorageService {
_cache['server_config_count'] = configs.length;
_cacheTimestamps['server_config_count'] = DateTime.now();
debugPrint('DEBUG: Server configs saved (${configs.length} configs)');
DebugLogger.log(
'Server configs saved (${configs.length} configs)',
scope: 'storage/optimized',
);
} catch (e) {
debugPrint('ERROR: Failed to save server configs: $e');
DebugLogger.log(
'Failed to save server configs: $e',
scope: 'storage/optimized',
);
rethrow;
}
}
@@ -194,7 +225,10 @@ class OptimizedStorageService {
return configs;
} catch (e) {
debugPrint('ERROR: Failed to retrieve server configs: $e');
DebugLogger.log(
'Failed to retrieve server configs: $e',
scope: 'storage/optimized',
);
return [];
}
}
@@ -275,7 +309,10 @@ class OptimizedStorageService {
final decoded = jsonDecode(jsonString) as List<dynamic>;
return decoded.map((item) => Conversation.fromJson(item)).toList();
} catch (e) {
debugPrint('ERROR: Failed to retrieve local conversations: $e');
DebugLogger.log(
'Failed to retrieve local conversations: $e',
scope: 'storage/optimized',
);
return [];
}
}
@@ -298,11 +335,15 @@ class OptimizedStorageService {
final jsonString = jsonEncode(lightweightConversations);
await _prefs.setString(_localConversationsKey, jsonString);
debugPrint(
'DEBUG: Saved ${conversations.length} local conversations (lightweight)',
DebugLogger.log(
'Saved ${conversations.length} local conversations (lightweight)',
scope: 'storage/optimized',
);
} catch (e) {
debugPrint('ERROR: Failed to save local conversations: $e');
DebugLogger.log(
'Failed to save local conversations: $e',
scope: 'storage/optimized',
);
}
}
@@ -331,9 +372,15 @@ class OptimizedStorageService {
key.contains('server'),
);
debugPrint('DEBUG: Auth data cleared in batch operation');
DebugLogger.log(
'Auth data cleared in batch operation',
scope: 'storage/optimized',
);
} catch (e) {
debugPrint('ERROR: Failed to clear auth data: $e');
DebugLogger.log(
'Failed to clear auth data: $e',
scope: 'storage/optimized',
);
}
}
@@ -344,9 +391,12 @@ class OptimizedStorageService {
_cache.clear();
_cacheTimestamps.clear();
debugPrint('DEBUG: All storage cleared');
DebugLogger.log('All storage cleared', scope: 'storage/optimized');
} catch (e) {
debugPrint('ERROR: Failed to clear all storage: $e');
DebugLogger.log(
'Failed to clear all storage: $e',
scope: 'storage/optimized',
);
}
}
@@ -366,21 +416,30 @@ class OptimizedStorageService {
void clearCache() {
_cache.clear();
_cacheTimestamps.clear();
debugPrint('DEBUG: Storage cache cleared');
DebugLogger.log('Storage cache cleared', scope: 'storage/optimized');
}
/// Migration from old storage service (one-time operation)
Future<void> migrateFromLegacyStorage() async {
try {
debugPrint('DEBUG: Starting migration from legacy storage');
DebugLogger.log(
'Starting migration from legacy storage',
scope: 'storage/optimized',
);
// This would be called once during app upgrade
// Implementation would depend on the specific migration needs
// For now, the SecureCredentialStorage already handles legacy migration
debugPrint('DEBUG: Legacy storage migration completed');
DebugLogger.log(
'Legacy storage migration completed',
scope: 'storage/optimized',
);
} catch (e) {
debugPrint('ERROR: Legacy storage migration failed: $e');
DebugLogger.log(
'Legacy storage migration failed: $e',
scope: 'storage/optimized',
);
}
}

View File

@@ -1,7 +1,7 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart' hide debugPrint;
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:share_handler/share_handler.dart' as sh;
@@ -85,7 +85,10 @@ final shareReceiverInitializerProvider = Provider<void>((ref) {
maybeProcessPending();
}
} catch (e) {
debugPrint('ShareReceiver: failed to get initial shared media: $e');
DebugLogger.log(
'ShareReceiver: failed to get initial shared media: $e',
scope: 'share',
);
}
});
@@ -98,7 +101,10 @@ final shareReceiverInitializerProvider = Provider<void>((ref) {
maybeProcessPending();
}
} catch (e) {
debugPrint('ShareReceiver: failed to parse shared media: $e');
DebugLogger.log(
'ShareReceiver: failed to parse shared media: $e',
scope: 'share',
);
}
});
@@ -197,11 +203,9 @@ Future<void> _processPayload(Ref ref, SharedPayload payload) async {
// Do NOT create a server chat here. The chat is created on first send
// (with server syncing + title generation) in chat_providers.dart.
} catch (e) {
debugPrint('ShareReceiver: failed to process payload: $e');
DebugLogger.log(
'ShareReceiver: failed to process payload: $e',
scope: 'share',
);
}
}
void debugPrint(String? message, {int? wrapWidth}) {
if (message == null) return;
DebugLogger.fromLegacy(message, scope: 'share');
}

View File

@@ -2,11 +2,6 @@ import 'package:socket_io_client/socket_io_client.dart' as io;
import '../models/server_config.dart';
import '../utils/debug_logger.dart';
void debugPrint(String? message, {int? wrapWidth}) {
if (message == null) return;
DebugLogger.fromLegacy(message, scope: 'socket');
}
class SocketService {
final ServerConfig serverConfig;
final bool websocketOnly;
@@ -97,7 +92,7 @@ class SocketService {
_socket = io.io(base, builder.build());
_socket!.on('connect', (_) {
debugPrint('Socket connected: ${_socket!.id}');
DebugLogger.log('Socket connected: ${_socket!.id}', scope: 'socket');
if (_authToken != null && _authToken!.isNotEmpty) {
_socket!.emit('user-join', {
'auth': {'token': _authToken},
@@ -106,15 +101,18 @@ class SocketService {
});
_socket!.on('connect_error', (err) {
debugPrint('Socket connect_error: $err');
DebugLogger.log('Socket connect_error: $err', scope: 'socket');
});
_socket!.on('reconnect_attempt', (attempt) {
debugPrint('Socket reconnect_attempt: $attempt');
DebugLogger.log('Socket reconnect_attempt: $attempt', scope: 'socket');
});
_socket!.on('reconnect', (attempt) {
debugPrint('Socket reconnected after $attempt attempts');
DebugLogger.log(
'Socket reconnected after $attempt attempts',
scope: 'socket',
);
if (_authToken != null && _authToken!.isNotEmpty) {
// Best-effort rejoin
_socket!.emit('user-join', {
@@ -124,11 +122,11 @@ class SocketService {
});
_socket!.on('reconnect_failed', (_) {
debugPrint('Socket reconnect_failed');
DebugLogger.log('Socket reconnect_failed', scope: 'socket');
});
_socket!.on('disconnect', (reason) {
debugPrint('Socket disconnected: $reason');
DebugLogger.log('Socket disconnected: $reason', scope: 'socket');
});
}

View File

@@ -6,11 +6,6 @@ import '../models/conversation.dart';
import 'secure_credential_storage.dart';
import '../utils/debug_logger.dart';
void debugPrint(String? message, {int? wrapWidth}) {
if (message == null) return;
DebugLogger.fromLegacy(message, scope: 'storage');
}
class StorageService {
final FlutterSecureStorage _secureStorage;
final SharedPreferences _prefs;
@@ -42,7 +37,10 @@ class StorageService {
try {
await _secureCredentialStorage.saveAuthToken(token);
} catch (e) {
debugPrint('Warning: Enhanced secure storage failed, using fallback: $e');
DebugLogger.log(
'Enhanced secure storage failed, using fallback: $e',
scope: 'storage',
);
await _secureStorage.write(key: _authTokenKey, value: token);
}
}
@@ -53,7 +51,10 @@ class StorageService {
final token = await _secureCredentialStorage.getAuthToken();
if (token != null) return token;
} catch (e) {
debugPrint('Warning: Enhanced secure storage failed, using fallback: $e');
DebugLogger.log(
'Enhanced secure storage failed, using fallback: $e',
scope: 'storage',
);
}
// Fallback to legacy storage
@@ -65,7 +66,10 @@ class StorageService {
try {
await _secureCredentialStorage.deleteAuthToken();
} catch (e) {
debugPrint('Warning: Failed to delete from enhanced storage: $e');
DebugLogger.log(
'Failed to delete from enhanced storage: $e',
scope: 'storage',
);
}
await _secureStorage.delete(key: _authTokenKey);
@@ -83,8 +87,9 @@ class StorageService {
final isSecureAvailable = await _secureCredentialStorage
.isSecureStorageAvailable();
if (!isSecureAvailable) {
debugPrint(
'DEBUG: Enhanced secure storage not available, using legacy storage',
DebugLogger.log(
'Enhanced secure storage not available, using legacy storage',
scope: 'storage',
);
throw Exception('Enhanced secure storage not available');
}
@@ -94,9 +99,15 @@ class StorageService {
username: username,
password: password,
);
debugPrint('DEBUG: Credentials saved using enhanced secure storage');
DebugLogger.log(
'Credentials saved using enhanced secure storage',
scope: 'storage',
);
} catch (e) {
debugPrint('Warning: Enhanced secure storage failed, using fallback: $e');
DebugLogger.log(
'Enhanced secure storage failed, using fallback: $e',
scope: 'storage',
);
// Fallback to legacy storage
try {
@@ -120,10 +131,14 @@ class StorageService {
);
}
debugPrint('DEBUG: Credentials saved using fallback storage');
DebugLogger.log(
'Credentials saved using fallback storage',
scope: 'storage',
);
} catch (fallbackError) {
debugPrint(
'ERROR: Both enhanced and fallback credential storage failed: $fallbackError',
DebugLogger.log(
'Both enhanced and fallback credential storage failed: $fallbackError',
scope: 'storage',
);
rethrow;
}
@@ -138,7 +153,10 @@ class StorageService {
return credentials;
}
} catch (e) {
debugPrint('Warning: Enhanced secure storage failed, using fallback: $e');
DebugLogger.log(
'Enhanced secure storage failed, using fallback: $e',
scope: 'storage',
);
}
// Fallback to legacy storage and migrate if found
@@ -153,7 +171,7 @@ class StorageService {
if (!decoded.containsKey('serverId') ||
!decoded.containsKey('username') ||
!decoded.containsKey('password')) {
debugPrint('Warning: Invalid saved credentials format');
DebugLogger.log('Invalid saved credentials format', scope: 'storage');
await deleteSavedCredentials();
return null;
}
@@ -170,16 +188,17 @@ class StorageService {
await _secureCredentialStorage.migrateFromOldStorage(legacyCredentials);
// If migration successful, clean up legacy storage
await _secureStorage.delete(key: _credentialsKey);
debugPrint(
'DEBUG: Successfully migrated credentials to enhanced storage',
DebugLogger.log(
'Successfully migrated credentials to enhanced storage',
scope: 'storage',
);
} catch (e) {
debugPrint('Warning: Failed to migrate credentials: $e');
DebugLogger.log('Failed to migrate credentials: $e', scope: 'storage');
}
return legacyCredentials;
} catch (e) {
debugPrint('Error loading saved credentials: $e');
DebugLogger.log('Error loading saved credentials: $e', scope: 'storage');
return null;
}
}
@@ -189,7 +208,10 @@ class StorageService {
try {
await _secureCredentialStorage.deleteSavedCredentials();
} catch (e) {
debugPrint('Warning: Failed to delete from enhanced storage: $e');
DebugLogger.log(
'Failed to delete from enhanced storage: $e',
scope: 'storage',
);
}
await _secureStorage.delete(key: _credentialsKey);
@@ -218,7 +240,10 @@ class StorageService {
final decoded = jsonDecode(jsonString);
if (decoded is! List) {
debugPrint('Warning: Server configs data is not a list, resetting');
DebugLogger.log(
'Server configs data is not a list, resetting',
scope: 'storage',
);
return [];
}
@@ -232,20 +257,24 @@ class StorageService {
item.containsKey('url')) {
configs.add(ServerConfig.fromJson(item));
} else {
debugPrint(
'Warning: Skipping invalid server config: missing required fields',
DebugLogger.log(
'Skipping invalid server config: missing required fields',
scope: 'storage',
);
}
}
} catch (e) {
debugPrint('Warning: Failed to parse server config: $e');
DebugLogger.log(
'Failed to parse server config: $e',
scope: 'storage',
);
// Continue with other configs
}
}
return configs;
} catch (e) {
debugPrint('Error loading server configs: $e');
DebugLogger.log('Error loading server configs: $e', scope: 'storage');
return [];
}
}
@@ -279,8 +308,9 @@ class StorageService {
try {
final decoded = jsonDecode(jsonString);
if (decoded is! List) {
debugPrint(
'Warning: Local conversations data is not a list, resetting',
DebugLogger.log(
'Local conversations data is not a list, resetting',
scope: 'storage',
);
return [];
}
@@ -296,20 +326,24 @@ class StorageService {
item.containsKey('updatedAt')) {
conversations.add(Conversation.fromJson(item));
} else {
debugPrint(
'Warning: Skipping invalid conversation: missing required fields',
DebugLogger.log(
'Skipping invalid conversation: missing required fields',
scope: 'storage',
);
}
}
} catch (e) {
debugPrint('Warning: Failed to parse conversation: $e');
DebugLogger.log('Failed to parse conversation: $e', scope: 'storage');
// Continue with other conversations
}
}
return conversations;
} catch (e) {
debugPrint('Error parsing local conversations: $e');
DebugLogger.log(
'Error parsing local conversations: $e',
scope: 'storage',
);
return [];
}
}
@@ -319,7 +353,7 @@ class StorageService {
final json = conversations.map((c) => c.toJson()).toList();
await _prefs.setString(_localConversationsKey, jsonEncode(json));
} catch (e) {
debugPrint('Error saving local conversations: $e');
DebugLogger.log('Error saving local conversations: $e', scope: 'storage');
}
}
@@ -350,21 +384,21 @@ class StorageService {
try {
await _secureCredentialStorage.clearAll();
} catch (e) {
debugPrint('Warning: Failed to clear enhanced storage: $e');
DebugLogger.log('Failed to clear enhanced storage: $e', scope: 'storage');
}
// Clear legacy storage
await _secureStorage.deleteAll();
await _prefs.clear();
debugPrint('DEBUG: All storage cleared');
DebugLogger.log('All storage cleared', scope: 'storage');
}
// Clear only auth-related data (keeping server configs and other settings)
Future<void> clearAuthData() async {
await deleteAuthToken();
await deleteSavedCredentials();
debugPrint('DEBUG: Auth data cleared');
DebugLogger.log('Auth data cleared', scope: 'storage');
}
/// Check if enhanced secure storage is available
@@ -372,7 +406,10 @@ class StorageService {
try {
return await _secureCredentialStorage.isSecureStorageAvailable();
} catch (e) {
debugPrint('Warning: Failed to check enhanced storage availability: $e');
DebugLogger.log(
'Failed to check enhanced storage availability: $e',
scope: 'storage',
);
return false;
}
}

View File

@@ -1,7 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart' hide debugPrint;
import 'package:flutter/material.dart';
import '../../core/models/chat_message.dart';
import '../../core/services/persistent_streaming_service.dart';
@@ -14,11 +14,6 @@ import '../../shared/widgets/themed_dialogs.dart';
import '../../shared/theme/theme_extensions.dart';
import '../utils/debug_logger.dart';
void debugPrint(String? message, {int? wrapWidth}) {
if (message == null) return;
DebugLogger.fromLegacy(message, scope: 'streaming/helper');
}
// Keep local verbosity toggle for socket logs
const bool kSocketVerboseLogging = false;
@@ -83,7 +78,10 @@ StreamSubscription<String> attachUnifiedChunkedStreaming({
),
controller: persistentController,
recoveryCallback: () async {
debugPrint('DEBUG: Attempting to recover interrupted stream');
DebugLogger.log(
'Attempting to recover interrupted stream',
scope: 'streaming/helper',
);
},
metadata: {
'conversationId': activeConversationId,

View File

@@ -1,15 +1,10 @@
import 'package:flutter/foundation.dart' hide debugPrint;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:conduit/l10n/app_localizations.dart';
import '../../shared/theme/theme_extensions.dart';
import 'navigation_service.dart';
import '../utils/debug_logger.dart';
void debugPrint(String? message, {int? wrapWidth}) {
if (message == null) return;
DebugLogger.fromLegacy(message, scope: 'errors/user-friendly');
}
/// User-friendly error messages and recovery actions
class UserFriendlyErrorHandler {
static final UserFriendlyErrorHandler _instance =
@@ -347,9 +342,12 @@ class UserFriendlyErrorHandler {
/// Log technical error details for debugging
void _logError(dynamic error) {
if (kDebugMode) {
debugPrint('ERROR: $error');
DebugLogger.log('$error', scope: 'errors/user-friendly');
if (error is Error) {
debugPrint('STACK TRACE: ${error.stackTrace}');
DebugLogger.log(
'STACK TRACE: ${error.stackTrace}',
scope: 'errors/user-friendly',
);
}
}