CodeBlanks Logo Icon CodeBlanks

Handler

Learn log handlers and output targets.

Handler

A handler is the function that processes log records. Logger.root.onRecord is a Stream<LogRecord>; you add a handler with .listen(...). The handler receives a record and writes it to the screen, a file or a remote server.

Example: Logger.root.onRecord.listen((r) => print(r.message));. This handler prints each record's message to the screen. You can add multiple handlers; each writes to a different target. For example one to the console, one to a file, one to a remote service. This is the way to flexibly manage logging output.

Multiple handlers

onRecord.listen can be called multiple times; each call adds a new handler. This is the way to send records to multiple places at once. For example one handler prints to the console while another increments a counter.

Example: Logger.root.onRecord.listen((r) => print('console: ${r.message}')); and Logger.root.onRecord.listen((r) => count++);. The first handler writes to the console; the second increments a counter. Both handlers run on every record. This shows the flexibility of logging; a single record stream can serve different purposes.

Practice Add two handlers

Add import 'package:logging/logging.dart';. In main add var count = 0; and Logger.root.level = Level.INFO;. Add two handlers: one that does print('console: ${r.message}') and one that does count++. Create final log = Logger('uygulama'); and call log.info('first'), log.info('second'). Finally add print('count: $count').

Starter code

main.dart
// import the logging package

void main() {
  // add two handlers: console print and counter, log two records, print count
}

Sample solution

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

void main() {
  var count = 0;
  Logger.root.level = Level.INFO;
  Logger.root.onRecord.listen((r) => print('console: ${r.message}'));
  Logger.root.onRecord.listen((r) => count++);
  final log = Logger('uygulama');
  log.info('first');
  log.info('second');
  print('count: $count');
}

Expected output

console: first
console: second
count: 2

Questions and answers

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

1 What type is onRecord?

  • String
  • void
  • int
  • Stream<LogRecord> Correct answer

Explanation: onRecord is a Stream<LogRecord>.

2 Match the handler parts

Term Meaning
onRecord Record stream
listen Adds a handler
LogRecord Record object
Stream Stream

3 The listen call

Question
Logger.root.onRecord.____((r) => print(r));
Answer
Logger.root.onRecord.listen((r) => print(r));

Explanation: you add a handler with onRecord.listen.

All lessons in Advanced