You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

86 lines
2.1 KiB

import 'package:flutter/foundation.dart';
enum LogLevel { debug, info, warning, error }
class LogEntry {
final DateTime timestamp;
final LogLevel level;
final String message;
final String? source;
LogEntry({required this.level, required this.message, this.source}) : timestamp = DateTime.now();
@override
String toString() {
final levelStr = level.toString().split('.').last.toUpperCase();
final timeStr = timestamp.toIso8601String();
final sourceStr = source != null ? ' [$source]' : '';
return '$timeStr $levelStr$sourceStr: $message';
}
}
class Logger with ChangeNotifier {
static final Logger _instance = Logger._internal();
final List<LogEntry> _logs = [];
bool _showTimestamps = true;
bool _showSource = true;
LogLevel _minimumLevel = LogLevel.debug;
factory Logger() {
return _instance;
}
Logger._internal();
List<LogEntry> get logs => List.unmodifiable(_logs);
bool get showTimestamps => _showTimestamps;
bool get showSource => _showSource;
LogLevel get minimumLevel => _minimumLevel;
void setMinimumLevel(LogLevel level) {
_minimumLevel = level;
notifyListeners();
}
void setShowTimestamps(bool show) {
_showTimestamps = show;
notifyListeners();
}
void setShowSource(bool show) {
_showSource = show;
notifyListeners();
}
void _addLog(LogEntry entry) {
print('Adding log: $entry');
if (entry.level.index >= _minimumLevel.index) {
_logs.add(entry);
notifyListeners();
if (kDebugMode) {
print(entry.toString());
}
}
}
void debug(String message, {String? source}) {
_addLog(LogEntry(level: LogLevel.debug, message: message, source: source));
}
void info(String message, {String? source}) {
_addLog(LogEntry(level: LogLevel.info, message: message, source: source));
}
void warning(String message, {String? source}) {
_addLog(LogEntry(level: LogLevel.warning, message: message, source: source));
}
void error(String message, {String? source}) {
_addLog(LogEntry(level: LogLevel.error, message: message, source: source));
}
void clear() {
_logs.clear();
notifyListeners();
}
}