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.
import 'package:flutter/material.dart';
import 'package:flutter_log_processor/flutter_log_processor.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize the log service
await LogService().initialize(
userId: 'demo_user',
sessionId: 'demo_session_${DateTime.now().millisecondsSinceEpoch}',
enableConsoleOutput: true,
minimumLevel: LogLevel.verbose,
maxStoredLogs: 5000,
);
// Initialize the event tracker
await EventTracker().initialize(
userId: 'demo_user',
sessionId: 'demo_session_${DateTime.now().millisecondsSinceEpoch}',
);
// Add some initial logs
LogService().info('Application started', tag: 'Startup');
LogService().debug('Services initialized', tag: 'Startup');
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Log Processor Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.deepPurple,
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.light,
),
cardTheme: CardTheme(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
darkTheme: ThemeData(
primarySwatch: Colors.deepPurple,
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.dark,
),
cardTheme: CardTheme(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
home: const DemoHomePage(),
);
}
}
class DemoHomePage extends StatefulWidget {
const DemoHomePage({Key? key}) : super(key: key);
@override
State<DemoHomePage> createState() => _DemoHomePageState();
}
class _DemoHomePageState extends State<DemoHomePage> {
int _logCount = 0;
int _eventCount = 0;
@override
void initState() {
super.initState();
_loadCounts();
// Track screen view
EventTracker().trackScreenView('HomeScreen');
}
Future<void> _loadCounts() async {
final logCount = await LogService().getLogsCount();
final events = await EventTracker().getAllEvents();
setState(() {
_logCount = logCount;
_eventCount = events.length;
});
}
void _generateSampleLogs() {
// Generate various types of logs
LogService().verbose('This is a verbose log message', tag: 'Demo');
LogService().debug('Debugging information here', tag: 'Debug');
LogService().info('User performed an action',
tag: 'UserAction',
metadata: {
'action': 'button_click',
'timestamp': DateTime.now().toString(),
},
);
LogService().warning('This is a warning message',
tag: 'Warning',
metadata: {'reason': 'Low memory'},
);
LogService().error('An error occurred',
tag: 'Error',
metadata: {
'error_code': 500,
'message': 'Internal server error',
},
);
// Track events
EventTracker().trackButtonClick('generate_logs_button');
EventTracker().track('logs_generated',
category: 'demo',
properties: {'count': 5},
);
_loadCounts();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Sample logs and events generated!'),
duration: Duration(seconds: 2),
),
);
}
void _simulateUserFlow() {
// Simulate a user flow with timed events
EventTracker().startTimedEvent('user_flow');
LogService().info('User flow started', tag: 'UserFlow');
Future.delayed(const Duration(milliseconds: 500), () {
LogService().debug('Step 1: Loading data', tag: 'UserFlow');
EventTracker().track('data_loaded', category: 'user_flow');
});
Future.delayed(const Duration(milliseconds: 1000), () {
LogService().debug('Step 2: Processing data', tag: 'UserFlow');
EventTracker().track('data_processed', category: 'user_flow');
});
Future.delayed(const Duration(milliseconds: 1500), () {
LogService().info('User flow completed', tag: 'UserFlow');
EventTracker().endTimedEvent('user_flow',
category: 'demo',
properties: {'steps': 3, 'success': true},
);
_loadCounts();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('User flow simulation completed!'),
duration: Duration(seconds: 2),
),
);
});
}
void _simulateError() {
try {
// Simulate an error
throw Exception('This is a simulated error for testing');
} catch (e, stackTrace) {
LogService().error(
'Caught an exception',
tag: 'ErrorHandling',
error: e,
stackTrace: stackTrace,
metadata: {
'error_type': 'Exception',
'handled': true,
},
);
EventTracker().track('error_caught',
category: 'error',
properties: {'type': 'simulated'},
);
_loadCounts();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Error logged with stack trace!'),
backgroundColor: Colors.red,
duration: Duration(seconds: 2),
),
);
}
}
void _openDashboard() {
EventTracker().trackButtonClick('open_dashboard_button');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const LogDashboard(
title: 'Log Processor Dashboard',
),
),
).then((_) {
_loadCounts();
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
theme.colorScheme.primary.withOpacity(0.1),
theme.colorScheme.secondary.withOpacity(0.1),
],
),
),
child: SafeArea(
child: Column(
children: [
_buildHeader(theme),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildStatsCards(theme),
const SizedBox(height: 24),
_buildActionCard(
theme,
'Generate Sample Logs',
'Create various types of log entries',
Icons.add_circle_outline,
Colors.blue,
_generateSampleLogs,
),
const SizedBox(height: 16),
_buildActionCard(
theme,
'Simulate User Flow',
'Track a complete user journey with timing',
Icons.timeline,
Colors.green,
_simulateUserFlow,
),
const SizedBox(height: 16),
_buildActionCard(
theme,
'Simulate Error',
'Generate an error log with stack trace',
Icons.error_outline,
Colors.red,
_simulateError,
),
const SizedBox(height: 32),
ElevatedButton.icon(
onPressed: _openDashboard,
icon: const Icon(Icons.dashboard),
label: const Text('Open Dashboard'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(20),
textStyle: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
],
),
),
),
],
),
),
),
);
}
Widget _buildHeader(ThemeData theme) {
return Container(
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
theme.colorScheme.primary,
theme.colorScheme.secondary,
],
),
boxShadow: [
BoxShadow(
color: theme.colorScheme.primary.withOpacity(0.3),
blurRadius: 10,
offset: const Offset(0, 4),
),
],
),
child: Column(
children: [
Icon(
Icons.analytics_outlined,
size: 64,
color: theme.colorScheme.onPrimary,
),
const SizedBox(height: 12),
Text(
'Flutter Log Processor',
style: theme.textTheme.headlineSmall?.copyWith(
color: theme.colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'Demo Application',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onPrimary.withOpacity(0.9),
),
),
],
),
);
}
Widget _buildStatsCards(ThemeData theme) {
return Row(
children: [
Expanded(
child: _buildStatCard(
theme,
'Logs',
_logCount.toString(),
Icons.list_alt,
Colors.blue,
),
),
const SizedBox(width: 16),
Expanded(
child: _buildStatCard(
theme,
'Events',
_eventCount.toString(),
Icons.event,
Colors.green,
),
),
],
);
}
Widget _buildStatCard(
ThemeData theme,
String title,
String value,
IconData icon,
Color color,
) {
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
color.withOpacity(0.8),
color,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: color.withOpacity(0.3),
blurRadius: 8,
offset: const Offset(0, 4),
),
],
),
child: Column(
children: [
Icon(icon, color: Colors.white, size: 32),
const SizedBox(height: 8),
Text(
value,
style: const TextStyle(
color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.bold,
),
),
Text(
title,
style: const TextStyle(
color: Colors.white70,
fontSize: 14,
),
),
],
),
);
}
Widget _buildActionCard(
ThemeData theme,
String title,
String description,
IconData icon,
Color color,
VoidCallback onTap,
) {
return Card(
elevation: 4,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.all(20),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: color.withOpacity(0.2),
borderRadius: BorderRadius.circular(12),
),
child: Icon(icon, color: color, size: 32),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
description,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.6),
),
),
],
),
),
const Icon(Icons.chevron_right),
],
),
),
),
);
}
}