Structured logging
- Dart course
- Advanced
- Lesson 65/83
- 5 min
Learn structured logging and JSON format.
Structured logging
Structured logging keeps records as structured data instead of plain text. It is usually in JSON format; each record contains level, message, timestamp and extra data fields. This makes records easier to search and audit.
In Dart you do this with jsonEncode from dart:convert. Inside the handler jsonEncode({'level': r.level.name, 'msg': r.message}) produces a JSON string. This is the standard format for sending logs to a system (for example an ELK stack).
JSON record fields
A structured log record usually contains these fields: level (severity), msg (message), ts (timestamp), logger (source). These fields are gathered in a Map and turned into JSON with jsonEncode.
Example: jsonEncode({'logger': r.loggerName, 'level': r.level.name, 'msg': r.message}). This produces JSON like {"logger":"uygulama","level":"INFO","msg":"started"}. This format is easily parsed by log collection systems; it is far more machine-friendly than plain text.
Practice A JSON log record
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({'level': r.level.name, 'msg': r.message}); print(record); });. Create final log = Logger('uygulama'); and call log.info('started').
Starter code
// import dart:convert and the logging package
void main() {
// print a structured record with jsonEncode inside the handler
}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({'level': r.level.name, 'msg': r.message});
print(record);
});
final log = Logger('uygulama');
log.info('started');
}Expected output
{"level":"INFO","msg":"started"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The jsonEncode call
var record = ____({'level': 'INFO', 'msg': 'started'});
var record = jsonEncode({'level': 'INFO', 'msg': 'started'});
Explanation: jsonEncode turns a Map into a JSON string.
2 Match the structured fields
| Term | Meaning |
|---|---|
jsonEncode |
JSON output |
level |
Level |
msg |
Message |
logger |
Source |
3 What format does structured logging use?
- JSON Correct answer
- HTML
- Plain text
- CSV
Explanation: structured logging is usually in JSON format.