Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ColoredTextPrintStrategy #8

Open
bartekpacia opened this issue Dec 23, 2021 · 0 comments
Open

Add ColoredTextPrintStrategy #8

bartekpacia opened this issue Dec 23, 2021 · 0 comments
Assignees
Labels
good first issue Good for newcomers

Comments

@bartekpacia
Copy link
Contributor

It'd be nice to have logs of different levels be colored appropriately.

Idea for implementation below (it was actually my take at it but I didn't have time to debug & finish it)

/// Instructs [LoggingBugfenderListener] to print colored text.
/// The color is based on the log level.
class ColoredTextPrintStrategy extends PrintStrategy {
  /// 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',
  };

  @override
  String print(LogRecord record) {
    final log = StringBuffer()
      ..writeAll(
        <String>[
          '[${record.level.name}]',
          if (record.loggerName.isNotEmpty) '${record.loggerName}:',
          record.message,
        ],
        ' ',
      );

    if (record.error != null) {
      log.write('\n${record.error}');
    }
    if (record.stackTrace != null) {
      log.write('\n${record.stackTrace}');
    }

    final color = _levelColors[record.level];
    if (color != null) {
      return '\x1B[${color}m$log\x1B[0m';
    } else {
      return log.toString();
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

2 participants