setUpLogging function

Future<void> setUpLogging({
  1. required Printer printer,
  2. bool structuredLogging = false,
  3. Level level = Level.ALL,
})

Set up logging

Implementation

Future<void> setUpLogging({
  required Printer printer,
  bool structuredLogging = false,
  Level level = Level.ALL,
}) async {
  /// Setup logging
  hierarchicalLoggingEnabled = true;
  Logger.root.level = level;
  Logger.root.onRecord.listen((record) {
    if (structuredLogging) {
      final jsonString = json.encode({
        'datetime': record.time.toIso8601String(),
        'level': record.level.name,
        'name': record.loggerName,
        'message': record.message,
        if (record.error != null) //
          'error': record.error.toString(),
        if (record.stackTrace != null) //
          'stack_trace': record.stackTrace.toString(),
      });
      printer.print(jsonString);
    } else {
      final level = record.level.name //
          .substring(0, math.min(record.level.name.length, 7))
          .padRight(8);
      final loggerName = record.loggerName //
          .substring(0, math.min(record.loggerName.length, 21))
          .padRight(22);
      var output = '${record.time} $level $loggerName ${record.message}';
      if (record.error != null) {
        output += '\nError: ';
        output += record.error.toString().split('\n').join('\n\t');
      }
      if (record.stackTrace != null) {
        output += '\n${record.stackTrace}'.split('\n').join('\n\t');
      }
      printer.print(_withColor(output, record.level));
      stdout.flush();
    }
  });
}