Logging in Dart

Here’s the translation of the Go logging example to Dart, along with explanations in Markdown format suitable for Hugo:

Our example demonstrates logging in Dart using the dart:developer library for basic logging and the logging package for more advanced features.

import 'dart:developer' as dev;
import 'package:logging/logging.dart';

void main() {
  // Simple logging using dart:developer
  dev.log('standard logger');

  // Configure the logging package
  Logger.root.level = Level.ALL;
  Logger.root.onRecord.listen((record) {
    print('${record.level.name}: ${record.time}: ${record.message}');
  });

  final logger = Logger('MyLogger');

  // Log with different levels
  logger.info('Info message');
  logger.warning('Warning message');

  // Logging with additional data
  logger.info('Message with data', {'key': 'value', 'number': 42});

  // Creating a child logger
  final childLogger = Logger('MyLogger.child');
  childLogger.fine('Fine message from child');

  // Logging to a custom destination (StringBuffer in this case)
  final buffer = StringBuffer();
  Logger('BufferLogger').onRecord.listen((record) {
    buffer.writeln('${record.level.name}: ${record.message}');
  });

  final bufferLogger = Logger('BufferLogger');
  bufferLogger.info('Hello from buffer logger');

  print('From buffer: ${buffer.toString()}');
}

To use this code, you’ll need to add the logging package to your pubspec.yaml file:

dependencies:
  logging: ^1.0.2

This example demonstrates various logging techniques in Dart:

  1. We start by using the simple log function from dart:developer for basic logging.

  2. We then configure the logging package, setting the root logger’s level and defining how log records should be printed.

  3. We create a logger instance and demonstrate logging at different levels (info, warning).

  4. The example shows how to log messages with additional structured data.

  5. We create a child logger to demonstrate hierarchical logging.

  6. Finally, we show how to log to a custom destination (a StringBuffer in this case) instead of the console.

When you run this program, you’ll see output similar to the following:

standard logger
INFO: 2023-08-22 11:45:16.123: Info message
WARNING: 2023-08-22 11:45:16.124: Warning message
INFO: 2023-08-22 11:45:16.125: Message with data
FINE: 2023-08-22 11:45:16.126: Fine message from child
From buffer: INFO: Hello from buffer logger

Note that the exact timestamps will depend on when you run the program.

This example demonstrates how to use logging in Dart for various scenarios, from simple console output to more structured logging with levels and custom destinations. The logging package provides a flexible system that can be adapted to different logging needs in your Dart applications.