Logging

suggest change

print is fine for a quick script, but a real program needs more from its logs: severity levels, the name of the component that logged, timestamps, errors with stack traces, and a way to turn noisy messages on and off without editing code.

In Dart you build this on:

This article covers:

print writes a line to standard output. Diagnostics should go to standard error so they don't mix with the program's real output (and survive dart run app.dart > out.txt):

import 'dart:io';

void main() {
  print('result: 42'); // program output -> stdout
  stderr.writeln('warning: config file not found, using defaults');
}

Output:

result: 42
warning: config file not found, using defaults

This works for small command line tools (see Console I/O). Once you want to filter by severity or by component, switch to package:logging.

Getting started with package:logging

Add the package:

dart pub add logging

This adds it to pubspec.yaml:

dependencies:
  logging: ^1.3.0

The package has three main pieces:

The package doesn't print anything on its own. You decide where records go by listening to Logger.root.onRecord:

import 'package:logging/logging.dart';

final log = Logger('app');

void main() {
  Logger.root.level = Level.ALL; // default is Level.INFO
  Logger.root.onRecord.listen((record) {
    print('${record.level.name}: ${record.loggerName}: ${record.message}');
  });

  log.fine('loading config');
  log.info('server started on port 8080');
  log.warning('disk 91% full');
  log.severe('cannot connect to database');
}

Output:

FINE: app: loading config
INFO: app: server started on port 8080
WARNING: app: disk 91% full
SEVERE: app: cannot connect to database

Set up the listener once, at the start of main. Libraries should only create loggers and log to them; they should never attach listeners or set the root level. That decision belongs to the application.

The usual convention is one logger per class or library, stored in a private static or top-level final:

class UserRepository {
  static final _log = Logger('UserRepository');

  void save(String name) {
    _log.fine('saving user $name');
  }
}

Logger('UserRepository') always returns the same instance for the same name, so creating it in several places is cheap and safe.

Levels

Levels from least to most severe, with their numeric values:

Level Value Use for
FINEST 300 very detailed tracing
FINER 400 detailed tracing
FINE 500 debugging information
CONFIG 700 configuration details
INFO 800 normal events (startup, requests)
WARNING 900 something unexpected, but the program continues
SEVERE 1000 an operation failed
SHOUT 1200 critical failures

Level.ALL (0) and Level.OFF (2000) are only used to configure a logger: they turn everything on or off.

A logger publishes a message only if its level is greater than or equal to the logger's level. The root logger starts at Level.INFO, so fine() messages are dropped until you lower it:

import 'package:logging/logging.dart';

void main() {
  Logger.root.onRecord.listen((r) => print('${r.level.name}: ${r.message}'));
  final log = Logger('app');

  log.fine('not shown, root level is INFO');
  log.info('shown');

  Logger.root.level = Level.WARNING;
  log.info('not shown anymore');
  log.warning('shown');

  print(Level.FINE < Level.INFO);
  print(log.isLoggable(Level.SEVERE));
}

Output:

INFO: shown
WARNING: shown
true
true

Levels are comparable, so if (record.level >= Level.WARNING) works in listeners.

Choosing the level at runtime

Hard-coding Level.ALL is not what you want in production. Read the level from an environment variable instead:

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

Level levelFromEnv() {
  final name = Platform.environment['LOG_LEVEL']?.toUpperCase();
  return Level.LEVELS.firstWhere(
    (l) => l.name == name,
    orElse: () => Level.INFO,
  );
}

void main() {
  Logger.root.level = levelFromEnv();
  Logger.root.onRecord.listen((r) => print('${r.level.name}: ${r.message}'));

  Logger('app').fine('detailed debug info');
  Logger('app').info('started');
}
$ dart run bin/app.dart
INFO: started
$ LOG_LEVEL=fine dart run bin/app.dart
FINE: detailed debug info
INFO: started

Level.LEVELS lists the predefined levels from ALL to OFF.

Avoiding expensive messages

The message is built before the call even if it's going to be dropped. If producing it is expensive, pass a function instead of a string. It's only called when the record is actually published:

import 'package:logging/logging.dart';

String dumpState() {
  print('(dumpState called)');
  return '{users: 1200, sessions: 87}';
}

void main() {
  Logger.root.onRecord.listen((r) => print('${r.level.name}: ${r.message}'));
  final log = Logger('app');

  log.fine(() => 'state: ${dumpState()}'); // dropped, dumpState() not called
  log.info(() => 'state: ${dumpState()}');

  if (log.isLoggable(Level.FINE)) {
    // guard a whole block of debug-only work
  }
}

Output:

(dumpState called)
INFO: state: {users: 1200, sessions: 87}

Hierarchical loggers

Logger names are dotted paths. Logger('app.db') is a child of Logger('app'), which is a child of Logger.root.

By default only the root logger has a level. To give individual loggers their own level (for example, debug just the database layer), set the top-level hierarchicalLoggingEnabled to true. Without it, setting level on a non-root logger throws UnsupportedError.

import 'package:logging/logging.dart';

void main() {
  hierarchicalLoggingEnabled = true;

  Logger.root.level = Level.INFO;
  Logger('app.db').level = Level.FINE; // more detail for the db layer only

  Logger.root.onRecord.listen((r) {
    print('[${r.loggerName}] ${r.level.name}: ${r.message}');
  });

  final http = Logger('app.http');
  final db = Logger('app.db');
  final pool = Logger('app.db.pool');

  http.fine('request headers: ...'); // dropped: inherits INFO from root
  http.info('GET /users');
  db.fine('SELECT * FROM users');
  pool.fine('connection 3 reused'); // inherits FINE from app.db

  print(pool.parent?.fullName);
  print(pool.level);
}

Output:

[app.http] INFO: GET /users
[app.db] FINE: SELECT * FROM users
[app.db.pool] FINE: connection 3 reused
app.db
FINE

A logger without its own level uses its parent's level, all the way up to the root.

With hierarchical logging enabled, a record is delivered to the onRecord listeners of its logger and of every ancestor. This lets you send one subsystem's logs somewhere extra:

Logger('app.audit').onRecord.listen((r) {
  auditSink.writeln('${r.time.toIso8601String()} ${r.message}');
});

Records from app.audit still reach the root listener too.

Logging errors and stack traces

Every logging method takes an optional error and stack trace after the message:

import 'package:logging/logging.dart';

final log = Logger('payments');

void charge(int cents) {
  if (cents <= 0) throw ArgumentError.value(cents, 'cents', 'must be positive');
}

void main() {
  Logger.root.onRecord.listen((r) {
    print('${r.level.name}: ${r.message}');
    if (r.error != null) print('  error: ${r.error}');
    if (r.stackTrace != null) print('  stack trace available');
  });

  try {
    charge(-5);
  } catch (e, st) {
    log.severe('charge failed', e, st);
  }
}

Output:

SEVERE: charge failed
  error: Invalid argument (cents): must be positive: -5
  stack trace available

Always pass the stack trace from catch (e, st). Without it you know what failed but not where. See Exceptions for more on catching errors.

To get a stack trace automatically for serious messages logged without one, set recordStackTraceAtLevel:

recordStackTraceAtLevel = Level.SEVERE;

Records at SEVERE and above that have no stack trace then get StackTrace.current, and an error of the form autogenerated stack trace for SEVERE <message> if none was given. It's off (Level.OFF) by default because capturing stack traces is slow.

Catching uncaught errors

Errors that escape into the event loop crash the program. Log them first with runZonedGuarded:

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

final log = Logger('app');

void main() {
  Logger.root.onRecord.listen((r) => print('${r.level.name}: ${r.message}: ${r.error}'));

  runZonedGuarded(() {
    Future.delayed(Duration.zero, () => throw StateError('lost connection'));
  }, (error, stack) {
    log.shout('uncaught error', error, stack);
  });
}

Output:

SHOUT: uncaught error: Bad state: lost connection

Formatting output

The listener controls the format. A typical one-line format includes time, level, logger name and message:

import 'package:logging/logging.dart';

String two(int n) => n.toString().padLeft(2, '0');
String three(int n) => n.toString().padLeft(3, '0');

String formatRecord(LogRecord r) {
  final t = r.time;
  final time = '${two(t.hour)}:${two(t.minute)}:${two(t.second)}.${three(t.millisecond)}';
  final buf = StringBuffer(
      '$time ${r.level.name.padRight(7)} ${r.loggerName}: ${r.message}');
  if (r.error != null) buf.write('\n  ${r.error}');
  if (r.stackTrace != null) buf.write('\n${r.stackTrace}');
  return buf.toString();
}

void main() {
  Logger.root.level = Level.ALL;
  Logger.root.onRecord.listen((r) => print(formatRecord(r)));

  Logger('app').info('started');
  Logger('app.db').fine('connected');
}

Output (times will differ):

14:03:27.512 INFO    app: started
14:03:27.515 FINE    app.db: connected

Colors in the terminal

ANSI escape codes make warnings and errors stand out. Only emit them when the terminal supports them:

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

String colorFor(Level level) {
  if (level >= Level.SEVERE) return '\x1B[31m'; // red
  if (level >= Level.WARNING) return '\x1B[33m'; // yellow
  if (level >= Level.INFO) return '\x1B[0m'; // default
  return '\x1B[90m'; // gray for FINE and below
}

void main() {
  final useColor = stdout.supportsAnsiEscapes;
  Logger.root.level = Level.ALL;
  Logger.root.onRecord.listen((r) {
    final line = '${r.level.name}: ${r.message}';
    print(useColor ? '${colorFor(r.level)}$line\x1B[0m' : line);
  });

  Logger('app')
    ..fine('debug detail')
    ..info('started')
    ..warning('slow query')
    ..severe('crashed');
}

When output is redirected to a file, supportsAnsiEscapes is false and you get plain text.

Structured (JSON) logging

Log aggregators (Elasticsearch, Loki, Google Cloud Logging, Datadog) work best with one JSON object per line. Searching for user == "alice" is much easier than parsing free text.

If you pass a non-string object as the message, package:logging keeps it in record.object and uses its toString() as record.message. Pass a Map to attach fields:

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

final log = Logger('auth');

void main() {
  Logger.root.onRecord.listen((r) {
    final entry = <String, Object?>{
      'time': r.time.toUtc().toIso8601String(),
      'level': r.level.name,
      'logger': r.loggerName,
      if (r.object is Map<String, Object?>)
        ...r.object as Map<String, Object?>
      else
        'message': r.message,
      if (r.error != null) 'error': r.error.toString(),
      if (r.stackTrace != null) 'stack': r.stackTrace.toString(),
    };
    print(jsonEncode(entry));
  });

  log.info('server ready');
  log.info({'message': 'login', 'user': 'alice', 'ms': 42});
  log.warning({'message': 'login failed', 'user': 'bob', 'attempt': 3});
}

Output (times will differ):

{"time":"2026-10-17T12:03:27.512301Z","level":"INFO","logger":"auth","message":"server ready"}
{"time":"2026-10-17T12:03:27.514120Z","level":"INFO","logger":"auth","message":"login","user":"alice","ms":42}
{"time":"2026-10-17T12:03:27.514120Z","level":"WARNING","logger":"auth","message":"login failed","user":"bob","attempt":3}

Field values must be JSON-encodable (numbers, strings, booleans, lists, maps, null); convert DateTime and custom objects to strings first. See JSON.

Never log secrets: passwords, tokens, API keys, full credit card numbers. Mask them before they reach the logger.

Logging to a file

Open an IOSink once and write each record to it. Remember to flush and close it before the program exits, or the last lines can be lost:

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

Future<void> main() async {
  final sink = File('app.log').openWrite(mode: FileMode.append);

  Logger.root.level = Level.ALL;
  final sub = Logger.root.onRecord.listen((r) {
    sink.writeln('${r.time.toIso8601String()} ${r.level.name} ${r.loggerName}: ${r.message}');
    if (r.level >= Level.WARNING) {
      stderr.writeln('${r.level.name}: ${r.message}'); // also show problems on the console
    }
  });

  final log = Logger('app');
  log.info('started');
  log.warning('cache directory missing, creating it');
  log.info('finished');

  await sub.cancel();
  await sink.flush();
  await sink.close();
}

Console output:

WARNING: cache directory missing, creating it

Contents of app.log (times will differ):

2026-10-17T14:03:27.512301 INFO app: started
2026-10-17T14:03:27.513822 WARNING app: cache directory missing, creating it
2026-10-17T14:03:27.513990 INFO app: finished

For long-running servers, it's usually better to log to stdout/stderr and let the environment (systemd, Docker, Kubernetes) collect and rotate the logs, than to manage log files yourself.

Adding context with zones

In a server, log lines from concurrent requests interleave. Attaching a request ID to every line makes it possible to follow one request.

Each LogRecord remembers the Zone it was logged in (record.zone). Store the request ID as a zone value and the listener can read it, without passing the ID to every function:

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

final log = Logger('server');

Future<void> loadUser() async {
  log.info('loading user'); // no request ID passed in
  await Future.delayed(const Duration(milliseconds: 10));
}

Future<void> handleRequest(String requestId) {
  return runZoned(() async {
    log.info('request started');
    await loadUser();
    log.info('request finished');
  }, zoneValues: {#requestId: requestId});
}

Future<void> main() async {
  Logger.root.onRecord.listen((r) {
    final id = r.zone?[#requestId] ?? '-';
    print('[$id] ${r.message}');
  });

  log.info('listening');
  await Future.wait([handleRequest('a1'), handleRequest('b2')]);
}

Output:

[-] listening
[a1] request started
[a1] loading user
[b2] request started
[b2] loading user
[a1] request finished
[b2] request finished

The zone value follows the request through every await, so even code deep inside loadUser gets the right ID.

dart:developer and Flutter

dart:developer has its own log function. Its messages go to the Dart VM service, so they appear in the DevTools Logging view and in the debug console of VS Code and Android Studio, with level, name and error shown separately. They do not appear when you run a program with plain dart run in a terminal.

import 'dart:developer' as developer;

void main() {
  developer.log('user signed in', name: 'app.auth', level: 800);

  try {
    throw const FormatException('bad token');
  } catch (e, st) {
    developer.log('token parse failed',
        name: 'app.auth', level: 1000, error: e, stackTrace: st);
  }
}

The level is just an int; the values used by package:logging (800 for INFO, 1000 for SEVERE) are a good convention.

In a Flutter app, a common setup is to use package:logging everywhere and forward records to developer.log, so they show up nicely in the IDE:

import 'dart:developer' as developer;
import 'package:logging/logging.dart';

void setupLogging() {
  Logger.root.level = Level.ALL;
  Logger.root.onRecord.listen((r) {
    developer.log(
      r.message,
      time: r.time,
      sequenceNumber: r.sequenceNumber,
      level: r.level.value,
      name: r.loggerName,
      zone: r.zone,
      error: r.error,
      stackTrace: r.stackTrace,
    );
  });
}

Flutter also has debugPrint (from package:flutter/foundation.dart), which throttles output so Android's logcat doesn't drop lines. In release builds, lower the level (for example Logger.root.level = kReleaseMode ? Level.WARNING : Level.ALL) so debug messages cost nothing.

Request logging in a Shelf server

Shelf's logRequests() middleware logs one line per request with time, duration, method, status and URL. By default it uses print; pass a logger callback to route it through package:logging (see REST APIs for Shelf basics):

import 'package:logging/logging.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;

final log = Logger('http');

Response hello(Request request) => Response.ok('hello');

Future<void> main() async {
  Logger.root.onRecord.listen((r) => print('${r.level.name}: ${r.message}'));

  final handler = const Pipeline()
      .addMiddleware(logRequests(
        logger: (message, isError) =>
            isError ? log.severe(message) : log.info(message),
      ))
      .addHandler(hello);

  final server = await io.serve(handler, 'localhost', 8080);
  log.info('listening on port ${server.port}');
}

After curl localhost:8080/hi the output looks like:

INFO: listening on port 8080
INFO: 2026-10-17T14:03:30.101221  0:00:00.002187 GET     [200] /hi

isError is true when the handler threw instead of returning a response.

Testing log output

Sometimes logging is the behavior you want to test, for example "an invalid charge logs a warning". Records are delivered synchronously, so a test can collect them in a list:

import 'dart:async';
import 'package:logging/logging.dart';
import 'package:test/test.dart';

class PaymentService {
  static final _log = Logger('PaymentService');

  bool charge(int cents) {
    if (cents <= 0) {
      _log.warning('rejected charge of $cents cents');
      return false;
    }
    _log.info('charged $cents cents');
    return true;
  }
}

void main() {
  late List<LogRecord> records;
  late StreamSubscription<LogRecord> sub;

  setUp(() {
    records = [];
    Logger.root.level = Level.ALL;
    sub = Logger.root.onRecord.listen(records.add);
  });

  tearDown(() => sub.cancel());

  test('invalid amount logs a warning', () {
    expect(PaymentService().charge(-5), isFalse);

    expect(records, hasLength(1));
    expect(records.single.level, Level.WARNING);
    expect(records.single.loggerName, 'PaymentService');
    expect(records.single.message, contains('-5'));
  });

  test('valid amount logs info', () {
    expect(PaymentService().charge(500), isTrue);
    expect(records.map((r) => r.level), [Level.INFO]);
  });
}

Cancel the subscription in tearDown so records from one test don't leak into the next. To remove every listener at once, use Logger.root.clearListeners().

Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents