Skip to content

Commit

Permalink
Implement ColoredTextPrintStrategy
Browse files Browse the repository at this point in the history
  • Loading branch information
Xezolpl committed Nov 7, 2024
1 parent c3c7d2f commit 5f10685
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions lib/src/print_strategy.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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, String?>{
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;
}
}
}

0 comments on commit 5f10685

Please sign in to comment.