CodeBlanks Logo Icon CodeBlanks

logging

Learn logging with the logging package.

The logging package

logging is Dart's standard logging package. It is imported with import 'package:logging/logging.dart';. The Logger class holds log records; Level is the record level; LogRecord represents a single record.

Example: final log = Logger('uygulama'); log.info('started');. Here a logger named 'uygulama' is created and an info record is written. By default records go nowhere; you must add a handler. With Logger.root.onRecord.listen(...) you capture records and write them to the screen or a file.

Adding a handler

A Logger holds records but gives no output by default. To see records you add a handler with Logger.root.onRecord.listen(...). The handler receives a LogRecord and processes it.

Example: Logger.root.onRecord.listen((r) => print('${r.level.name}: ${r.message}'));. This handler prints each record as 'INFO: message'. r.level.name gives the level name; r.message gives the record message. You also set the minimum level with Logger.root.level = Level.INFO; records below this level are ignored.

Practice Set up a logger and log a record

Add import 'package:logging/logging.dart';. In main set the minimum level with Logger.root.level = Level.INFO;. Add a handler with Logger.root.onRecord.listen((r) => print('${r.level.name}: ${r.message}'));. Create a logger with final log = Logger('uygulama'); and log with log.info('started').

Starter code

main.dart
// import the logging package

void main() {
  // set root level, add handler, log a record
}

Sample solution

main.dart
import 'package:logging/logging.dart';

void main() {
  Logger.root.level = Level.INFO;
  Logger.root.onRecord.listen((r) => print('${r.level.name}: ${r.message}'));
  final log = Logger('uygulama');
  log.info('started');
}

Expected output

INFO: started

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the logging package do?

  • Provides logging Correct answer
  • Manages databases
  • Makes HTTP requests
  • Manipulates DOM

Explanation: the logging package provides logging.

2 Creating a Logger

Question
final log = ____('uygulama');
Answer
final log = Logger('uygulama');

Explanation: Logger('uygulama') creates a logger.

3 Match the logging parts

Term Meaning
logging Logging package
Logger Logger
Level Level
LogRecord Record

All lessons in Advanced