App Log Manager

pub package License Flutter

A comprehensive Flutter logging package that provides structured, contextual, and feature-rich logging capabilities for your Flutter applications.

✨ Features

🎯 Core Logging Features

  • Multiple Log Levels: Fatal, Error, Warning, Info, Debug, Verbose with priority-based filtering
  • Structured Logging: Rich log entries with context, tags, and metadata
  • Real-time Streaming: Live log monitoring with stream-based architecture
  • Context Tracking: User ID, session ID, and correlation ID support
  • Source Tracking: Automatic capture of source file, method, and line number

πŸ”§ Advanced Capabilities

  • Performance Monitoring: Built-in performance metrics and timing
  • API Call Logging: Comprehensive HTTP request/response logging
  • User Action Tracking: User interaction and behavior analytics
  • Security Event Logging: Security-focused event tracking
  • Business Event Analytics: Custom business metrics and events
  • Crash Reporting: Automatic crash detection and reporting
  • Navigation Logging: Route change and navigation tracking

πŸ› οΈ Developer Experience

  • Interface-based Design: Dependency inversion with AppLogger interface
  • Factory Pattern: Pre-configured logger instances for different environments
  • Multiple Output Options: Console, file, custom storage backends
  • Safe Type Handling: Built-in null safety and type conversion
  • Rich Formatting: Emoji icons, ANSI colors, and customizable formatters
  • Testing Support: Dedicated test logger with in-memory storage

πŸ“± Production Features

  • Environment Configurations: Development, production, and testing presets
  • File Logging: Persistent file-based logging for production apps
  • Log Sanitization: Automatic removal of sensitive data (passwords, emails, etc.)
  • Memory Management: Configurable log retention and cleanup
  • Export Capabilities: JSON export and log sharing functionality

πŸš€ Getting Started

Installation

Add this to your package's pubspec.yaml file:

dependencies:
  app_logger_manager: ^1.0.0

Then run:

flutter pub get

Quick Start

import 'package:app_logger_manager/app_logger_manager.dart';

void main() {
  // Create a logger instance
  final logger = LogManagerFactory.createDefault();

  // Basic logging
  logger.info('Application started');
  logger.debug('Debug information', context: {'userId': '123'});
  logger.error('Something went wrong', error: exception, stackTrace: stackTrace);

  runApp(MyApp());
}

πŸ“– Usage

Basic Logging

final logger = LogManagerFactory.createDefault();

// Different log levels
logger.verbose('Detailed debug information');
logger.debug('Debug message for developers');
logger.info('General information');
logger.warning('Warning message');
logger.error('Error occurred', error: exception);
logger.fatal('Critical system failure', error: exception, stackTrace: stackTrace);

Structured Logging with Context

logger.info(
  'User logged in',
  tag: 'AUTH',
  context: {
    'userId': user.id,
    'email': user.email,
    'timestamp': DateTime.now().toIso8601String(),
    'platform': Platform.operatingSystem,
  },
);

User and Session Tracking

// Set user context
logger.currentUserId = 'user_123';
logger.currentSessionId = 'session_456';
logger.currentCorrelationId = 'request_789';

// All subsequent logs will include this context
logger.info('User action performed');

Performance Monitoring

// Log performance metrics
logger.logPerformance(
  'database_query',
  Duration(milliseconds: 150),
  metrics: {
    'query': 'SELECT * FROM users',
    'resultCount': 42,
    'cacheHit': false,
  },
);

API Call Logging

logger.logApiCall(
  'POST',
  '/api/users',
  statusCode: 201,
  duration: Duration(milliseconds: 200),
  requestBody: {'name': 'John', 'email': 'john@example.com'},
  responseBody: {'id': 123, 'status': 'created'},
);

User Action Tracking

// Log user interactions
logger.logUserAction(
  'button_click',
  screen: 'profile_page',
  parameters: {
    'button_id': 'save_profile',
    'section': 'personal_info',
  },
);

// Log feature usage
logger.logFeatureUsage(
  'premium_feature',
  action: 'activated',
  properties: {'plan': 'premium', 'trial': false},
);

Business Events and Analytics

// Log business events
logger.logBusinessEvent(
  'purchase_completed',
  properties: {
    'amount': 29.99,
    'currency': 'USD',
    'product_id': 'premium_plan',
    'payment_method': 'credit_card',
  },
);

// Log security events
logger.logSecurity(
  'failed_login_attempt',
  severity: 'medium',
  details: {
    'ip_address': '192.168.1.1',
    'user_agent': 'Mozilla/5.0...',
    'attempt_count': 3,
  },
);

Real-time Log Streaming

// Listen to log stream
logger.logStream.listen((logEntry) {
  print('New log: ${logEntry.level.label} - ${logEntry.message}');

  // Update UI, send to analytics, etc.
  if (logEntry.level == LogLevel.error) {
    showErrorNotification(logEntry.message);
  }
});

Factory Pattern - Pre-configured Loggers

// Development logger with verbose output
final devLogger = LogManagerFactory.createDevelopmentLogger(
  defaultTag: 'DEV',
  defaultContext: {'environment': 'development'},
);

// Production logger with file output
final prodLogger = LogManagerFactory.createProductionLogger(
  minimumLogLevel: LogLevel.warning,
  logFilePath: '/path/to/app.log',
  defaultTag: 'PROD',
);

// Console-only logger
final consoleLogger = LogManagerFactory.createConsoleLogger(
  minimumLogLevel: LogLevel.debug,
);

// API monitoring logger
final apiLogger = LogManagerFactory.createApiLogger(
  defaultTag: 'API',
);

// Testing logger with in-memory storage
final testLogger = LogManagerFactory.createTestLogger();

🎯 Advanced Usage

Custom Log Storage

// Implement custom storage
class CustomLogStorage implements LogStorage {
  @override
  Future<void> store(LogEntry entry) async {
    // Send to remote server, database, etc.
  }

  @override
  Future<List<LogEntry>> retrieve({
    int? count,
    LogLevel? minimumLevel,
  }) async {
    // Return stored logs
  }
}

// Use custom storage
final logger = LogManagerFactory.createWithStorage(
  storage: CustomLogStorage(),
);

Error Handling Setup

void main() {
  final logger = LogManagerFactory.createProductionLogger();

  // Setup Flutter error handling
  FlutterError.onError = (details) {
    logger.logCrash(
      'Flutter Error',
      details.exception,
      details.stack ?? StackTrace.current,
      context: {
        'library': details.library,
        'context': details.context?.toString(),
      },
    );
  };

  // Setup platform error handling
  PlatformDispatcher.instance.onError = (error, stack) {
    logger.logCrash('Platform Error', error, stack);
    return true;
  };

  runApp(MyApp());
}

Log Filtering and Retrieval

// Retrieve recent logs
final recentLogs = await logger.getLogs(
  count: 100,
  level: LogLevel.error,
  tag: 'API',
);

// Export logs
final jsonLogs = await logger.exportLogs(
  startDate: DateTime.now().subtract(Duration(days: 7)),
  endDate: DateTime.now(),
  format: ExportFormat.json,
);

πŸ”§ Configuration

Log Levels

The package supports 8 log levels with priority-based filtering:

Level Priority Use Case
none 0 Disable all logging
fatal 100 Critical system failures
error 200 Error conditions
warning 300 Warning conditions
info 400 General information
debug 500 Debug information
verbose 600 Detailed debug info
all 999 Enable all logging

Environment Configuration

// Development
final devLogger = AppLoggerImpl(
  minimumLogLevel: LogLevel.verbose,
  enableConsoleOutput: true,
  enableFileOutput: false,
  defaultTag: 'DEV',
);

// Production
final prodLogger = AppLoggerImpl(
  minimumLogLevel: LogLevel.warning,
  enableConsoleOutput: false,
  enableFileOutput: true,
  logFilePath: 'app.log',
  defaultTag: 'PROD',
);

πŸ§ͺ Testing

The package includes comprehensive testing support:

void main() {
  group('Logging Tests', () {
    late AppLogger logger;

    setUp(() {
      logger = LogManagerFactory.createTestLogger();
    });

    test('should log messages correctly', () async {
      logger.info('Test message', context: {'test': true});

      final logs = await logger.getLogs(count: 1);
      expect(logs.length, equals(1));
      expect(logs.first.message, equals('Test message'));
      expect(logs.first.level, equals(LogLevel.info));
    });
  });
}

πŸ“± Example App

The package includes a comprehensive example app demonstrating all features:

cd example
flutter run

The example app showcases:

  • Different log levels and formatting
  • Real-time log streaming
  • Performance monitoring
  • API call logging
  • User action tracking
  • Security and business events

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ“Š Changelog

See CHANGELOG.md for a detailed list of changes and version history.

Libraries

app_logger_manager
A comprehensive Flutter app log manager package