flutter_log_processor 2.0.0 copy "flutter_log_processor: ^2.0.0" to clipboard
flutter_log_processor: ^2.0.0 copied to clipboard

A comprehensive Flutter package for logging, event tracking, and log preprocessing with an integrated dashboard.

📊 Flutter Log Processor #

A powerful, production-ready Flutter package for advanced logging, event tracking, and analytics with a stunning integrated dashboard.

Version Flutter License Dart

FeaturesInstallationQuick StartDashboardExamplesDocumentation


✨ Features #

🎯 Core Capabilities #

  • 📝 Multi-Level Logging - 6 severity levels (Verbose, Debug, Info, Warning, Error, Fatal)
  • 🎯 Advanced Event Tracking - Track user interactions, screen views, and custom events with timing support
  • 📊 Beautiful Dashboard - Premium, modern UI for visualizing logs and events with real-time statistics
  • 💾 Persistent Storage - Automatic local storage of logs and events using SharedPreferences
  • 🔍 Smart Filtering - Advanced search and filtering by level, tag, date range, and custom queries
  • 📤 Multi-Format Export - Export logs as JSON, CSV, or formatted text
  • 🎨 Fully Customizable - Custom themes, colors, and UI components
  • ⚡ High Performance - Minimal overhead with efficient storage and lazy-loading UI

📈 Analytics & Insights #

  • Pattern Detection - Automatically identify repeated errors and issues
  • Statistical Analysis - Comprehensive statistics and metrics generation
  • Time-Based Grouping - Group and analyze logs by time periods
  • Session Tracking - Track user sessions and associate logs with specific users
  • Metadata Support - Attach custom metadata to logs for enhanced debugging

🎨 Premium UI Components #

  • Interactive Charts - Beautiful visualizations of log data
  • Color-Coded Entries - Easy identification of log levels
  • Real-Time Updates - Live dashboard updates as logs are added
  • Responsive Design - Optimized for all screen sizes
  • Dark/Light Themes - Built-in theme support

🏗️ Architecture #

Flutter Log Processor Architecture

The package is built with a clean, modular architecture featuring:

  • LogService - Singleton pattern for centralized logging with thread-safe operations
  • EventTracker - Dedicated service for tracking user events and analytics
  • LogProcessor - Powerful utilities for log analysis and pattern detection
  • LogDashboard - Beautiful, customizable UI for visualizing and managing logs
  • Local Persistence - Efficient, secure local storage with configurable retention policies

📱 Dashboard Preview #

Dashboard UI

The integrated dashboard provides a comprehensive view of your app's logs and events:

  • 📊 Overview Tab - Real-time statistics, charts, and key metrics
  • 📝 Logs Tab - Searchable, filterable log entries with color coding
  • 🎯 Events Tab - Event timeline with categories and properties
  • 📤 Export Options - One-click export to JSON, CSV, or text
  • 🎨 Modern Design - Premium UI with smooth animations and transitions

📦 Installation #

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

dependencies:
  flutter_log_processor: ^2.0.0

Then run:

flutter pub get

🚀 Quick Start #

1️⃣ Initialize the Logger #

import 'package:flutter_log_processor/flutter_log_processor.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize the log service with configuration
  await LogService().initialize(
    userId: 'user123',
    sessionId: 'session456',
    enableConsoleOutput: true,
    minimumLevel: LogLevel.verbose,
  );
  
  runApp(MyApp());
}

2️⃣ Add Logs #

// Simple logging with different severity levels
LogService().info('User logged in');
LogService().warning('Low memory warning');
LogService().error('Failed to load data', 
  tag: 'Network',
  metadata: {'url': 'https://api.example.com', 'statusCode': 404},
);

// Debug logging with tags
LogService().debug('Cache hit', 
  tag: 'Cache',
  metadata: {'key': 'user_profile', 'ttl': 3600},
);

// Fatal errors with stack traces
LogService().fatal('Critical system failure', 
  tag: 'System',
  metadata: {'component': 'AuthService'},
);

3️⃣ Track Events #

// Initialize event tracker
await EventTracker().initialize(
  userId: 'user123',
  sessionId: 'session456',
);

// Track simple events
EventTracker().track('button_clicked', 
  category: 'interaction',
  properties: {
    'button_name': 'login',
    'screen': 'HomeScreen',
  },
);

// Track screen views
EventTracker().trackScreenView('HomeScreen');

// Track timed events (e.g., API calls, loading times)
EventTracker().startTimedEvent('api_call');
// ... perform operation ...
EventTracker().endTimedEvent('api_call', 
  category: 'network',
  properties: {
    'endpoint': '/api/users',
    'duration_ms': 245,
  },
);

// Track button clicks
EventTracker().trackButtonClick('submit_form', 
  properties: {'form_type': 'registration'},
);

4️⃣ Show Dashboard #

import 'package:flutter_log_processor/flutter_log_processor.dart';

// Navigate to the integrated dashboard
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => LogDashboard(
      title: 'My App Logs',
      primaryColor: Colors.deepPurple,
      showLogs: true,
      showEvents: true,
      showStatistics: true,
    ),
  ),
);

🔧 Advanced Usage #

Custom Log Filtering #

final filter = LogFilter(
  levels: {LogLevel.error, LogLevel.warning},
  searchQuery: 'network',
  startDate: DateTime.now().subtract(Duration(hours: 24)),
  endDate: DateTime.now(),
  tag: 'API',
);

final logs = await LogService().getAllLogs();
final filtered = logs.where((log) => filter.matches(log)).toList();

Log Processing & Statistics #

final logs = await LogService().getAllLogs();
final stats = LogProcessor.processLogs(logs);

print('Total logs: ${stats.totalLogs}');
print('Errors: ${stats.errorsCount}');
print('Warnings: ${stats.warningsCount}');
print('Info: ${stats.infoCount}');

// Find patterns (repeated errors)
final patterns = LogProcessor.findPatterns(logs);
for (final pattern in patterns) {
  print('Pattern detected: ${pattern.message} (${pattern.count} occurrences)');
}

// Group logs by time period
final grouped = LogProcessor.groupLogsByPeriod(logs, period: TimePeriod.hour);

Export Logs #

final logs = await LogService().getAllLogs();

// Export as JSON
final json = LogExporter.exportLogsAsJson(logs);

// Export as CSV
final csv = LogExporter.exportLogsAsCsv(logs);

// Export as formatted text
final text = LogExporter.exportLogsAsText(logs);

// Save to file or share with user
final file = await saveToFile(json, 'logs.json');
await Share.shareFiles([file.path]);

Custom UI Components #

// Use individual viewers for custom layouts
LogViewer(
  logs: myLogs,
  showFilters: true,
  onRefresh: () => _loadLogs(),
  primaryColor: Colors.blue,
)

EventViewer(
  events: myEvents,
  onRefresh: () => _loadEvents(),
  groupByCategory: true,
)

// Statistics widget
LogStatisticsWidget(
  statistics: stats,
  showCharts: true,
)

Session Management #

// Update user/session context
LogService().setUserId('new_user_id');
LogService().setSessionId('new_session_id');

// Clear old logs
await LogService().clearOldLogs(olderThan: Duration(days: 7));

// Clear all logs
await LogService().clearLogs();

📖 API Reference #

LogService #

The main singleton service for managing logs.

Initialization:

  • initialize({userId, sessionId, enableConsoleOutput, minimumLevel}) - Initialize the service with configuration

Logging Methods:

  • verbose(message, {tag, metadata}) - Log verbose message (detailed debugging)
  • debug(message, {tag, metadata}) - Log debug message (development)
  • info(message, {tag, metadata}) - Log informational message
  • warning(message, {tag, metadata}) - Log warning message
  • error(message, {tag, metadata, stackTrace}) - Log error message
  • fatal(message, {tag, metadata, stackTrace}) - Log fatal/critical error

Management Methods:

  • getAllLogs() - Retrieve all stored logs
  • clearLogs() - Clear all logs from storage
  • clearOldLogs({olderThan}) - Clear logs older than specified duration
  • setUserId(userId) - Update user ID for subsequent logs
  • setSessionId(sessionId) - Update session ID for subsequent logs
  • getLogCount() - Get total number of stored logs

EventTracker #

Service for tracking user events and analytics.

Initialization:

  • initialize({userId, sessionId}) - Initialize the tracker

Tracking Methods:

  • track(eventName, {category, properties}) - Track a custom event
  • startTimedEvent(eventName) - Start timing an event
  • endTimedEvent(eventName, {category, properties}) - End timing and record event
  • trackScreenView(screenName, {properties}) - Track screen/page view
  • trackButtonClick(buttonName, {properties}) - Track button click event

Management Methods:

  • getAllEvents() - Retrieve all stored events
  • clearEvents() - Clear all events from storage
  • getEventCount() - Get total number of stored events

LogProcessor #

Static utility class for processing and analyzing logs.

Statistical Methods:

  • processLogs(logs) - Generate comprehensive statistics from logs
  • processEvents(events) - Generate statistics from events

Analysis Methods:

  • findPatterns(logs, {minOccurrences}) - Detect repeated patterns in logs
  • groupLogsByPeriod(logs, {period}) - Group logs by time period (hour/day/week)
  • getLogsByLevel(logs, level) - Filter logs by severity level
  • getLogsByTag(logs, tag) - Filter logs by tag

LogDashboard #

Main dashboard widget for visualizing logs and events.

Properties:

  • title (String) - Dashboard title
  • showLogs (bool) - Show logs tab (default: true)
  • showEvents (bool) - Show events tab (default: true)
  • showStatistics (bool) - Show statistics tab (default: true)
  • primaryColor (Color?) - Custom primary color for theming
  • enableExport (bool) - Enable export functionality (default: true)

Features:

  • Tabbed interface with overview, logs, events, and export
  • Real-time updates and statistics
  • Interactive filtering and search
  • Beautiful charts and visualizations

💡 Example App #

import 'package:flutter/material.dart';
import 'package:flutter_log_processor/flutter_log_processor.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize services
  await LogService().initialize(
    userId: 'demo_user',
    enableConsoleOutput: true,
  );
  await EventTracker().initialize(userId: 'demo_user');
  
  // Add sample logs
  LogService().info('App started', tag: 'Lifecycle');
  LogService().debug('Initializing services', tag: 'Startup');
  
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Log Processor Demo',
      theme: ThemeData(
        primarySwatch: Colors.deepPurple,
        useMaterial3: true,
      ),
      home: DemoHomePage(),
    );
  }
}

class DemoHomePage extends StatelessWidget {
  void _generateSampleLogs() {
    // Generate diverse sample logs
    LogService().verbose('Verbose log entry', tag: 'Debug');
    LogService().debug('User action detected', tag: 'Analytics');
    LogService().info('Data loaded successfully', tag: 'Data');
    LogService().warning('Cache about to expire', tag: 'Cache');
    LogService().error('Network request failed', 
      tag: 'Network',
      metadata: {'url': 'https://api.example.com', 'code': 500},
    );
    LogService().fatal('Critical error occurred', 
      tag: 'System',
      metadata: {'component': 'DatabaseService'},
    );
    
    // Track sample events
    EventTracker().trackScreenView('HomeScreen');
    EventTracker().trackButtonClick('generate_logs_button');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Log Processor v2.0'),
        elevation: 2,
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(20),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.analytics_outlined, size: 80, color: Colors.deepPurple),
              SizedBox(height: 20),
              Text(
                'Flutter Log Processor Demo',
                style: Theme.of(context).textTheme.headlineSmall,
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 10),
              Text(
                'Track logs and events with ease',
                style: Theme.of(context).textTheme.bodyMedium,
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 40),
              ElevatedButton.icon(
                onPressed: () {
                  _generateSampleLogs();
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Sample logs and events generated!'),
                      backgroundColor: Colors.green,
                    ),
                  );
                },
                icon: Icon(Icons.add_circle_outline),
                label: Text('Generate Sample Logs'),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 30, vertical: 15),
                ),
              ),
              SizedBox(height: 20),
              ElevatedButton.icon(
                onPressed: () {
                  EventTracker().trackButtonClick('open_dashboard_button');
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => LogDashboard(
                        title: 'My App Dashboard',
                        primaryColor: Colors.deepPurple,
                      ),
                    ),
                  );
                },
                icon: Icon(Icons.dashboard),
                label: Text('Open Dashboard'),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 30, vertical: 15),
                  backgroundColor: Colors.deepPurple,
                  foregroundColor: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

📸 Screenshots #

The dashboard includes:

  • 📊 Overview Tab - Statistics, charts, and key metrics at a glance
  • 📝 Logs Tab - Searchable log entries with advanced filtering
  • 🎯 Events Tab - Event timeline with categorization and properties
  • 📤 Export Tab - One-click export to JSON, CSV, or text
  • 🎨 Beautiful UI - Modern, premium design with smooth animations

💡 Best Practices #

  1. 🚀 Initialize Early - Initialize services in main() before running the app
  2. 🏷️ Use Tags - Tag logs consistently for better organization and filtering
  3. 📋 Add Metadata - Include relevant metadata for enhanced debugging and analysis
  4. 📊 Track Meaningful Events - Focus on user interactions and critical app events
  5. 🗑️ Clean Up Periodically - Clear old logs to manage storage effectively
  6. 👤 Set User Context - Always set userId and sessionId for proper tracking
  7. ⚡ Log Appropriately - Use appropriate log levels (don't log everything as error)
  8. 🔒 Privacy First - Avoid logging sensitive user data (passwords, tokens, etc.)

⚡ Performance #

  • Efficient Storage - Optimized local storage using SharedPreferences
  • Configurable Limits - Maximum of 10,000 logs by default (customizable)
  • Minimal Overhead - Negligible performance impact on main thread
  • Lazy Loading - UI components use lazy loading for smooth scrolling
  • Smart Caching - Intelligent caching reduces redundant operations
  • Batch Operations - Batch writes for improved performance

🆕 What's New in v2.0.0 #

  • Enhanced dashboard UI with better performance
  • Improved filtering and search capabilities
  • Better error pattern detection
  • More export format options
  • Enhanced documentation and examples
  • Performance optimizations
  • Bug fixes and stability improvements

📄 License #

MIT License - see LICENSE file for details


🤝 Support & Contributing #


🙏 Acknowledgments #

Made with 💙 by SaifAlmajd for the Flutter community

Star ⭐ this repository if you find it helpful!


1
likes
140
points
117
downloads

Publisher

verified publishersaifalmajd.blogspot.com

Weekly Downloads

A comprehensive Flutter package for logging, event tracking, and log preprocessing with an integrated dashboard.

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

flutter, intl, path_provider, shared_preferences

More

Packages that depend on flutter_log_processor