flex_logger_console 1.0.1
flex_logger_console: ^1.0.1 copied to clipboard
Console logging provider for FlexLogger - provides formatted console output with colors and log levels
example/lib/main.dart
import 'package:flex_logger/flex_logger.dart';
import 'package:flex_logger_console/flex_logger_console.dart';
import 'package:flutter/material.dart';
/// Colors matching FlexLog classes (debug, info, success, etc.) for button styling.
abstract final class _LogColors {
static const debug = Color(0xFF00BCD4); // DebugLog cyan
static const info = Color(0xFF2196F3); // InfoLog blue
static const success = Color(0xFF4CAF50); // SuccessLog green
static const warning = Color(0xFFFF9800); // WarningLog orange
static const error = Color(0xFFF44336); // ErrorLog red
static const critical = Color(0xFFD32F2F); // CriticalLog dark red
static const custom = Color(0xFFFFEB3B); // CustomLog yellow
static const multiLine = Color(0xFF2196F3); // Info blue
static const exception = Color(0xFFF44336); // Error red
}
/// Custom log using Flutter Color with ColorAnsiPen extension.
/// Demonstrates how to create custom logs with any Flutter color.
final class ExampleCustomLog extends FlexLog {
ExampleCustomLog(String super.message)
: super(
level: FlexLogLevel.info,
tag: 'CUSTOM',
color: _LogColors.custom,
);
}
/// Custom log with a unique color using ColorAnsiPen extension.
final class PurpleLog extends FlexLog {
PurpleLog(String super.message)
: super(
level: FlexLogLevel.info,
tag: 'PURPLE',
color: Colors.purple,
);
}
/// Available console settings presets for demonstration.
enum SettingsPreset {
defaultSettings('Default', '─', 80, 'HH:mm:ss.SSS'),
compact('Compact', '─', 60, 'HH:mm:ss'),
wide('Wide', '═', 120, 'yyyy-MM-dd HH:mm:ss'),
minimal('Minimal', '-', 50, 'HH:mm')
;
final String label;
final String lineSymbol;
final int maxLineWidth;
final String datePattern;
const SettingsPreset(this.label, this.lineSymbol, this.maxLineWidth, this.datePattern);
ConsoleFormatter toFormatter() => ConsoleFormatter(
lineSymbol: lineSymbol,
maxLineWidth: maxLineWidth,
enableColors: true,
dateFormat: DateFormat(datePattern),
);
}
/// Available filter presets for demonstration.
enum FilterPreset {
none('All logs', FilterType.acceptAll),
warningAndAbove('Warning+', FilterType.minLevel),
errorOnly('Error+', FilterType.minLevelError),
developmentOnly('Dev only', FilterType.development),
errorAndCriticalTypes('Error & Critical types', FilterType.typeFilter),
compositeExample('Composite (Info+ AND NOT Debug)', FilterType.composite)
;
final String label;
final FilterType type;
const FilterPreset(this.label, this.type);
LogFilter toFilter() {
return switch (type) {
FilterType.acceptAll => const AcceptAllFilter(),
FilterType.minLevel => const MinLevelFilter(FlexLogLevel.warning),
FilterType.minLevelError => const MinLevelFilter(FlexLogLevel.error),
FilterType.development => const DevelopmentOnlyFilter(),
FilterType.typeFilter => CompositeLogFilter.or([
const TypeFilter<ErrorLog>(),
const TypeFilter<CriticalLog>(),
]),
FilterType.composite => CompositeLogFilter.and([
const MinLevelFilter(FlexLogLevel.info),
CompositeLogFilter.not(const TypeFilter<DebugLog>()),
]),
};
}
}
/// Types of filters available in the example.
enum FilterType {
acceptAll,
minLevel,
minLevelError,
development,
typeFilter,
composite,
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
FlexLogger.instance.configure(
providers: [
ConsoleLoggerProvider(
formatter: ConsoleFormatter(
enableColors: true,
maxLineWidth: 80,
// Default dateFormat: HH:mm:ss.SSS (with milliseconds)
),
),
],
);
await FlexLogger.instance.initialize();
FlexLogger.instance.info('Flex Logger Console example started');
FlexLogger.instance.debug('Debug message');
FlexLogger.instance.success('Console provider only – no file logging');
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flex Logger Console Example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
useMaterial3: true,
),
home: const MyHomePage(title: 'Console Example'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({super.key, required this.title});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
SettingsPreset _selectedPreset = SettingsPreset.defaultSettings;
FilterPreset _selectedFilter = FilterPreset.none;
Future<void> _reconfigureLogger() async {
await FlexLogger.instance.dispose();
FlexLogger.instance.configure(
providers: [
ConsoleLoggerProvider(
formatter: _selectedPreset.toFormatter(),
filter: _selectedFilter.toFilter(),
),
],
);
await FlexLogger.instance.initialize();
FlexLogger.instance.info(
'Logger reconfigured: ${_selectedPreset.label}, filter: ${_selectedFilter.label}',
);
}
@override
void dispose() {
// IMPORTANT: Always dispose logger before app terminates
FlexLogger.instance.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Click buttons to test colored console output',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
const Text('Check your terminal/console for colored logs'),
const SizedBox(height: 24),
// Settings configuration
_buildSettingsSection(),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 16),
// Standard log levels
const Text(
'Standard Log Levels:',
style: TextStyle(fontWeight: FontWeight.w600),
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
alignment: WrapAlignment.center,
children: [
ElevatedButton(
onPressed: () => FlexLogger.instance.debug('Debug message from button'),
style: ElevatedButton.styleFrom(
backgroundColor: _LogColors.debug,
),
child: const Text('Debug'),
),
ElevatedButton(
onPressed: () => FlexLogger.instance.info('Info message from button'),
style: ElevatedButton.styleFrom(
backgroundColor: _LogColors.info,
),
child: const Text('Info'),
),
ElevatedButton(
onPressed: () => FlexLogger.instance.success('Success message from button'),
style: ElevatedButton.styleFrom(
backgroundColor: _LogColors.success,
),
child: const Text('Success'),
),
ElevatedButton(
onPressed: () => FlexLogger.instance.warning('Warning message from button'),
style: ElevatedButton.styleFrom(
backgroundColor: _LogColors.warning,
),
child: const Text('Warning'),
),
ElevatedButton(
onPressed: () => FlexLogger.instance.error('Error message from button'),
style: ElevatedButton.styleFrom(
backgroundColor: _LogColors.error,
foregroundColor: Colors.white,
),
child: const Text('Error'),
),
ElevatedButton(
onPressed: () => FlexLogger.instance.critical('Critical message from button'),
style: ElevatedButton.styleFrom(
backgroundColor: _LogColors.critical,
foregroundColor: Colors.white,
),
child: const Text('Critical'),
),
],
),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 16),
// Custom log examples
const Text(
'Custom Logs (using ColorAnsiPen extension):',
style: TextStyle(fontWeight: FontWeight.w600),
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
alignment: WrapAlignment.center,
children: [
ElevatedButton(
onPressed: () {
FlexLogger.instance.logCustom(
ExampleCustomLog('Custom yellow log'),
);
},
style: ElevatedButton.styleFrom(
backgroundColor: _LogColors.custom,
foregroundColor: Colors.black87,
),
child: const Text('Yellow Custom'),
),
ElevatedButton(
onPressed: () {
FlexLogger.instance.logCustom(
PurpleLog('Custom purple log using Colors.purple'),
);
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purple,
foregroundColor: Colors.white,
),
child: const Text('Purple Custom'),
),
ElevatedButton(
onPressed: () {
FlexLogger.instance.info('Multi-line message:\nLine 1\nLine 2\nLine 3');
},
style: ElevatedButton.styleFrom(
backgroundColor: _LogColors.multiLine,
),
child: const Text('Multi-line'),
),
ElevatedButton(
onPressed: () {
try {
throw Exception('Test exception');
} catch (e, stackTrace) {
FlexLogger.instance.error(e.toString(), e, stackTrace);
}
},
style: ElevatedButton.styleFrom(
backgroundColor: _LogColors.exception,
foregroundColor: Colors.white,
),
child: const Text('Exception'),
),
],
),
],
),
),
),
);
}
Future<void> _selectPreset(SettingsPreset preset) async {
if (preset == _selectedPreset) return;
setState(() => _selectedPreset = preset);
await _reconfigureLogger();
}
Future<void> _selectFilter(FilterPreset filter) async {
if (filter == _selectedFilter) return;
setState(() => _selectedFilter = filter);
await _reconfigureLogger();
}
Widget _buildSettingsSection() {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Console Settings:',
style: TextStyle(fontWeight: FontWeight.w600, fontSize: 16),
),
const SizedBox(height: 12),
const Text('Style:', style: TextStyle(fontWeight: FontWeight.w500)),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: SettingsPreset.values.map((preset) {
final selected = preset == _selectedPreset;
return FilterChip(
label: Text(preset.label),
selected: selected,
onSelected: (_) => _selectPreset(preset),
);
}).toList(),
),
const SizedBox(height: 16),
const Text('Filter:', style: TextStyle(fontWeight: FontWeight.w500)),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: FilterPreset.values.map((filter) {
final selected = filter == _selectedFilter;
return FilterChip(
label: Text(filter.label),
selected: selected,
onSelected: (_) => _selectFilter(filter),
);
}).toList(),
),
const SizedBox(height: 12),
Text(
'Current: lineSymbol="${_selectedPreset.lineSymbol}", '
'width=${_selectedPreset.maxLineWidth}, '
'dateFormat="${_selectedPreset.datePattern}"',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
);
}
}