flutter_log_processor 2.0.0
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.
Features • Installation • Quick Start • Dashboard • Examples • Documentation
✨ 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 #

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 #

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 messagewarning(message, {tag, metadata})- Log warning messageerror(message, {tag, metadata, stackTrace})- Log error messagefatal(message, {tag, metadata, stackTrace})- Log fatal/critical error
Management Methods:
getAllLogs()- Retrieve all stored logsclearLogs()- Clear all logs from storageclearOldLogs({olderThan})- Clear logs older than specified durationsetUserId(userId)- Update user ID for subsequent logssetSessionId(sessionId)- Update session ID for subsequent logsgetLogCount()- 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 eventstartTimedEvent(eventName)- Start timing an eventendTimedEvent(eventName, {category, properties})- End timing and record eventtrackScreenView(screenName, {properties})- Track screen/page viewtrackButtonClick(buttonName, {properties})- Track button click event
Management Methods:
getAllEvents()- Retrieve all stored eventsclearEvents()- Clear all events from storagegetEventCount()- Get total number of stored events
LogProcessor #
Static utility class for processing and analyzing logs.
Statistical Methods:
processLogs(logs)- Generate comprehensive statistics from logsprocessEvents(events)- Generate statistics from events
Analysis Methods:
findPatterns(logs, {minOccurrences})- Detect repeated patterns in logsgroupLogsByPeriod(logs, {period})- Group logs by time period (hour/day/week)getLogsByLevel(logs, level)- Filter logs by severity levelgetLogsByTag(logs, tag)- Filter logs by tag
LogDashboard #
Main dashboard widget for visualizing logs and events.
Properties:
title(String) - Dashboard titleshowLogs(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 themingenableExport(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 #
- 🚀 Initialize Early - Initialize services in
main()before running the app - 🏷️ Use Tags - Tag logs consistently for better organization and filtering
- 📋 Add Metadata - Include relevant metadata for enhanced debugging and analysis
- 📊 Track Meaningful Events - Focus on user interactions and critical app events
- 🗑️ Clean Up Periodically - Clear old logs to manage storage effectively
- 👤 Set User Context - Always set userId and sessionId for proper tracking
- ⚡ Log Appropriately - Use appropriate log levels (don't log everything as error)
- 🔒 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 #
- Issues: Found a bug? Open an issue
- Features: Have an idea? Request a feature
- Questions: Need help? Email me at syfalmjd11@gmail.com
🙏 Acknowledgments #
Made with 💙 by SaifAlmajd for the Flutter community
Star ⭐ this repository if you find it helpful!