Skip to content

Add ColoredTextPrintStrategy #8

@bartekpacia

Description

@bartekpacia

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();
    }
  }
}

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions