Last active
July 2, 2025 09:48
-
-
Save estebanfeldman/32cc3e58a357847efc10d14754c5b829 to your computer and use it in GitHub Desktop.
Simple App Logger Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'package:logger/logger.dart'; | |
| class TimestampPrinter extends LogPrinter { | |
| final LogPrinter _realPrinter; | |
| TimestampPrinter(this._realPrinter); | |
| @override | |
| List<String> log(LogEvent event) { | |
| final timestamp = DateTime.now().millisecondsSinceEpoch; | |
| final realLogs = _realPrinter.log(event); | |
| return realLogs.map((line) => '[$timestamp] $line').toList(); | |
| } | |
| } | |
| /// A simple, lazily-instantiated singleton that wraps `package:logger`. | |
| class AppLogger { | |
| // 1) Private constructor | |
| AppLogger._internal() { | |
| _logger = Logger( | |
| printer: TimestampPrinter(PrettyPrinter( | |
| methodCount: 2, | |
| excludePaths: ['package:flutter_pro_new/utils/app_logger.dart'], | |
| )), | |
| ); | |
| } | |
| // 2) The single static instance | |
| static final AppLogger _instance = AppLogger._internal(); | |
| // 3) Factory constructor that always returns the same instance | |
| factory AppLogger() => _instance; | |
| // 4) Underlying Logger (late-initialised in the private ctor) | |
| late final Logger _logger; | |
| void debug(String message) { | |
| _logger.d(message); | |
| } | |
| void error(String message) { | |
| _logger.e(message); | |
| } | |
| void warning(String message) { | |
| _logger.w(message); | |
| } | |
| /// Access to the wrapped `Logger` in case you need extra features | |
| Logger get raw => _logger; | |
| } | |
| final appLogger = AppLogger(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment