CodeBlanks Logo Icon CodeBlanks

Logger

Learn Logger instances and hierarchy.

Logger hierarchy

The Logger class works hierarchically with dot-separated names. Logger('uygulama') is a parent logger; Logger('uygulama.veritabani') is its child. The child inherits the parent's level.

Example: when Logger.root.level = Level.INFO; both Logger('uygulama') and Logger('uygulama.veritabani') record INFO and above. r.loggerName tells which logger the record came from. This is the clean way to split logs by module in large applications; each module uses its own child logger.

Parent and child logger

When a child logger writes a record the record also propagates to parent loggers. With Logger.root.onRecord.listen you capture all records in a single handler. With r.loggerName you tell which logger the record came from.

Example: final appLog = Logger('uygulama'); final dbLog = Logger('uygulama.veritabani');. The record appLog.info('started') has name 'uygulama'; dbLog.info('opened') has name 'uygulama.veritabani'. In the handler you print r.loggerName to see the source. This makes record tracking easier in large systems.

Practice Parent and child logger records

Add import 'package:logging/logging.dart';. In main add Logger.root.level = Level.INFO; and Logger.root.onRecord.listen((r) => print('${r.loggerName}: ${r.message}'));. Create final appLog = Logger('uygulama'); and final dbLog = Logger('uygulama.veritabani');. Call appLog.info('started') and dbLog.info('opened').

Starter code

main.dart
// import the logging package

void main() {
  // set root level and handler, log parent and child records
}

Sample solution

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

void main() {
  Logger.root.level = Level.INFO;
  Logger.root.onRecord.listen((r) => print('${r.loggerName}: ${r.message}'));
  final appLog = Logger('uygulama');
  final dbLog = Logger('uygulama.veritabani');
  appLog.info('started');
  dbLog.info('opened');
}

Expected output

uygulama: started
uygulama.veritabani: opened

Questions and answers

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

1 Match the logger hierarchy

Term Meaning
Logger('a.b') Child logger
'.' Hierarchy separator
parent Parent
child Child

2 What does Logger('a.b') represent?

  • A single logger
  • Two separate loggers
  • A hierarchical child logger Correct answer
  • Sibling loggers

Explanation: Logger('a.b') is a child logger of 'a'.

3 Creating a child logger

Question
final dbLog = ____('uygulama.veritabani');
Answer
final dbLog = Logger('uygulama.veritabani');

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

All lessons in Advanced