Summary - Logging
- Dart course
- Advanced
- Lesson 66/83
- 5 min
Combine logging, levels and handlers to write a log system.
Summary - Logging
In this group we learned logging management with Dart. The logging package holds logs; Level (SEVERE, WARNING, INFO, FINE) filters; Logger works with hierarchical names; handler processes records; structured logging produces machine-friendly JSON output.
In this summary we bring all parts together with structured logging. The program sets up a logger, produces JSON records via a handler and writes an info record. This is a small but working example of a real application's logging layer.
Practice Structured logging summary
Add import 'dart:convert'; and import 'package:logging/logging.dart';. In main add Logger.root.level = Level.INFO; and a handler: Logger.root.onRecord.listen((r) { final record = jsonEncode({'logger': r.loggerName, 'level': r.level.name, 'msg': r.message}); print(record); });. Create final log = Logger('summary'); and call log.info('done').
Starter code
// import dart:convert and the logging package
void main() {
// structured logging: print JSON with logger, level, msg fields
}Sample solution
import 'dart:convert';
import 'package:logging/logging.dart';
void main() {
Logger.root.level = Level.INFO;
Logger.root.onRecord.listen((r) {
final record = jsonEncode({'logger': r.loggerName, 'level': r.level.name, 'msg': r.message});
print(record);
});
final log = Logger('summary');
log.info('done');
}Expected output
{"logger":"summary","level":"INFO","msg":"done"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is the standard logging package?
- sqflite
- logging Correct answer
- args
- dcli
Explanation: logging is Dart's standard logging package.
2 Match the logging concepts
| Term | Meaning |
|---|---|
logging |
Package |
Level |
Level |
Logger |
Logger |
onRecord |
Handler stream |
3 The jsonEncode call
final record = ____({'logger': r.loggerName, 'level': r.level.name, 'msg': r.message});
final record = jsonEncode({'logger': r.loggerName, 'level': r.level.name, 'msg': r.message});
Explanation: jsonEncode turns a Map into a JSON string.