diff --git a/lib/src/print_strategy.dart b/lib/src/print_strategy.dart index 3dc8b14..9f94b42 100644 --- a/lib/src/print_strategy.dart +++ b/lib/src/print_strategy.dart @@ -46,3 +46,43 @@ class PlainTextPrintStrategy extends PrintStrategy { return log.toString(); } } + +/// Instructs [LoggingBugfenderListener] to print colored text. +/// The color is based on the log level. +/// The colored text works only if the output terminal supports ANSI escape +/// sequences. In most cases you can check if ANSI escapes are supported, using +/// `kIsWeb || io.stdout.supportsAnsiEscapes`. +class ColoredTextPrintStrategy extends PlainTextPrintStrategy { + /// Creates a strategy that prints colored plain text. + const ColoredTextPrintStrategy(); + + static final _levelColors = { + Level.FINEST: '8', + Level.FINER: '8', + Level.FINE: '8', + Level.CONFIG: null, + Level.INFO: '12', + Level.WARNING: '208', + Level.SEVERE: '196', + Level.SHOUT: '199', + }; + + /// ANSI Control Sequence Introducer, signals the terminal for new settings. + static const ansiEsc = '\x1B['; + + /// Reset all colors and options to terminal defaults. + static const ansiDefault = '${ansiEsc}0m'; + + @override + String print(LogRecord record) { + final log = super.print(record); + + final color = _levelColors[record.level]; + + if (color != null) { + return '${ansiEsc}38;5;${color}m$log$ansiDefault'; + } else { + return log; + } + } +}