platform/packages/pretty_logging/lib/pretty_logging.dart

51 lines
1.4 KiB
Dart
Raw Normal View History

2019-08-09 22:53:32 +00:00
import 'package:logging/logging.dart';
import 'package:io/ansi.dart';
/// Prints the contents of a [LogRecord] with pretty colors.
///
/// By passing [omitError], you can omit printing the error of a given
/// [LogRecord].
///
/// You can also pass a custom [printFunction] or [logColorChooser].
void prettyLog(LogRecord record,
2021-03-09 16:40:38 +00:00
{bool Function(LogRecord)? omitError,
void Function(String)? printFunction,
AnsiCode Function(Level)? logColorChooser}) {
2019-08-09 22:53:32 +00:00
logColorChooser ??= chooseLogColor;
omitError ??= (_) => false;
printFunction ??= print;
var code = logColorChooser(record.level);
2021-03-09 16:40:38 +00:00
if (record.error == null) printFunction(code.wrap(record.toString())!);
2019-08-09 22:53:32 +00:00
if (record.error != null) {
var err = record.error;
if (omitError(record)) return;
2021-03-09 16:40:38 +00:00
printFunction(code.wrap(record.toString() + '\n')!);
printFunction(code.wrap(err.toString())!);
2019-08-09 22:53:32 +00:00
if (record.stackTrace != null) {
2021-03-09 16:40:38 +00:00
printFunction(code.wrap(record.stackTrace.toString())!);
2019-08-09 22:53:32 +00:00
}
}
}
/// Chooses a color based on the logger [level].
AnsiCode chooseLogColor(Level level) {
if (level == Level.SHOUT) {
return backgroundRed;
} else if (level == Level.SEVERE) {
return red;
} else if (level == Level.WARNING) {
return yellow;
} else if (level == Level.INFO) {
return cyan;
} else if (level == Level.CONFIG ||
level == Level.FINE ||
level == Level.FINER ||
level == Level.FINEST) {
return lightGray;
}
return resetAll;
}