Dart
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.
Exercise 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').
Show example solution
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');
}
Test yourself
-
What type is onRecord?
- String
- void
- int
- Stream<LogRecord>
Show answer
Stream<LogRecord> — onRecord is a Stream<LogRecord>.
-
Match the handler parts
- onRecord
- Record stream
- listen
- Adds a handler
- LogRecord
- Record object
- Stream
- Stream
-
The listen call
Logger.root.onRecord.____((r) => print(r));
Show answer
Logger.root.onRecord.listen((r) => print(r));
Next lesson: Structured logging