Skip to main content

One post tagged with "dart"

View All Tags

· 10 min read
Elisha Sterngold

A Flutter app on an Android phone, an iPhone, a browser and a desktop, each with its own log (Logcat, the unified log, the browser console, stdout) whose lines crumble away; one line from every device joins a single route to the Shipbook console, which lists each device's session with its logs and an error's stack trace

Flutter Logging: print, debugPrint, dart:developer, Error Handlers and Remote Logging​

Flutter gives you one codebase for Android, iOS, the web and the desktop, and logging is where that promise gets thin.

At your desk, print works and the line shows up in the terminal. In production, every Dart log line ends up wherever the platform puts it — Logcat on Android, the unified log on iOS, the browser's console on the web, and standard output on macOS, Windows and Linux, where nobody sees it once the app is installed. And Flutter adds a few traps of its own: one popular logging package logs nothing at all in a release build, and an error thrown during build shows your user a gray box while the explanation goes to a log on their device that nobody will read.

This guide covers every way to write a log in Flutter, where each one goes, how to catch the errors Flutter swallows, what happens in release builds, and how to get the logs from your users' devices.

Flutter has three built-in ways to write a log line, and they don't go to the same place.

import 'dart:developer' as developer;
import 'package:flutter/foundation.dart';

print('Applying coupon $code');
debugPrint('Order $orderId submitted');
developer.log(
'Payment failed',
name: 'checkout',
level: 1000, // SEVERE in package:logging's scale
error: error,
stackTrace: stack,
);

print comes from dart:core. The line shows in the flutter run terminal and your IDE, and it's written to the platform's log: a Logcat line with the tag flutter on Android, the unified log on iOS, the browser console on the web, and the process's standard output on macOS, Windows and Linux. Flutter's default lints flag it (avoid_print), for a reason we'll get to.

debugPrint comes from Flutter's foundation library. By default it throttles its output, because Android rate-limits logging and drops lines when an app writes too many at once. A long JSON response or a big stack trace printed with print can lose its middle; with debugPrint it arrives whole. You can also pass wrapWidth to wrap long lines.

log from dart:developer is the structured one. It takes a name (the source, like a tag), a numeric level, an error and a stackTrace, and it sends them to the debugger — DevTools' Logging view, where you can filter by name and expand the error. It doesn't go to Logcat or to flutter logs, and a release build has no debugger to receive it. On the web, a debug build sends it to the browser console with console.debug, and in a release build log does nothing at all. It's an excellent tool while you develop, and it's invisible everywhere else.

Logging Packages: logger and logging​

Most Flutter apps don't stop at print. Two packages cover most of the rest, and each has a default worth knowing.

logger prints pretty, colored, boxed output with levels from trace to fatal:

import 'package:logger/logger.dart';

final logger = Logger();

logger.d('Applying coupon $code');
logger.e('Payment failed', error: error, stackTrace: stack);

Here's the default worth knowing: Logger() uses a DevelopmentFilter, which only logs while asserts run — that is, in debug builds. In release mode it omits every log. That's a sensible choice for console output, and a surprise the day you go looking for a production log that was never written. Pass filter: ProductionFilter() if you want release builds to log.

logging is the Dart team's package. It gives you named, hierarchical loggers with levels from FINEST to SHOUT, and it doesn't print anything by itself. Every record goes to a stream, and you decide where it goes:

import 'package:logging/logging.dart';

final _log = Logger('CheckoutPage');

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

// Anywhere in the app
_log.info('Order $orderId submitted');
_log.warning('Payment retry ${attempt + 1} of 3', error, stack);

If you've used Timber on Android, onRecord plays the role of its trees: your code only ever calls _log, and where lines go is decided in one place. Forget the listener and the records go nowhere.

Errors Flutter Catches — and the Ones It Doesn't​

The most important lines in a Flutter app are the ones you didn't write: the errors. Flutter routes them through two handlers, and by default both of them only print.

FlutterError.onError receives the errors Flutter catches itself — in build, layout, paint, and gesture callbacks. Its default dumps the error to the device log. When the error happens during build, Flutter replaces the broken widget using ErrorWidget.builder: the red error screen in debug mode, and a gray box in release mode. The user sees part of the screen go gray; the stack trace is in a log on their device.

PlatformDispatcher.instance.onError receives the errors that happen outside Flutter's callbacks — an await that throws with no try around it, a failed platform channel call. By default it only prints them.

To do anything with these errors, set both handlers before runApp:

import 'dart:ui';
import 'package:flutter/material.dart';

void main() {
FlutterError.onError = (details) {
FlutterError.presentError(details); // keep printing it to the console
report(details.exception, details.stack);
};
PlatformDispatcher.instance.onError = (error, stack) {
report(error, stack);
return true; // handled
};
runApp(const ShopApp());
}

Note the dart:ui import — PlatformDispatcher isn't exported by material.dart. And report is the question: printing it again puts it in the same log nobody reads.

Reading Logs from a Device​

When the app runs on a connected device, flutter logs shows the output of print and debugPrint without starting a debug session — useful on a tester's phone or when the app was launched by something else.

Below Flutter, the platform tools still work. On Android, Flutter's lines are Logcat lines with the tag flutter:

# Only Flutter's lines
adb logcat -s flutter

# Dump what's in the buffers to a file and exit
adb logcat -d > android-log.txt

On iOS, the app's output is in Xcode's console when you run from Xcode, and in the Console app on a Mac with the device connected. Everything about those tools — Logcat filters, adb bugreport, the log buffers, unified logging — works the same for a Flutter app; I covered them in Android Logging in Kotlin and iOS Logging in Swift.

On the web, print and debugPrint lines are in the browser's DevTools console, and in a debug build developer.log calls show there too, at the Verbose level. That's your browser, or a user's if you can talk them through opening DevTools.

On the desktop, the engine writes these lines to standard output. On macOS that's the terminal you started the app from — unlike iOS, nothing goes to the unified log, so the Console app shows none of it. On Windows, the runner Flutter generates attaches a console only when the app was started from one or under a debugger; started from the Start menu, the lines go nowhere. On Linux, they go wherever the desktop sends a launched app's output, on many distributions the systemd journal.

What these tools have in common is that you're there: a phone you can plug in, a browser you can open DevTools in, a terminal you started the app from.

Logging in Release Builds​

print and debugPrint both still run in a release build. They cost time on every user's device, and anyone with adb on Android, or with DevTools on the web, can read them — which is why avoid_print exists. Flutter's answer is kDebugMode and kReleaseMode, compile-time constants from foundation:

if (kDebugMode) {
debugPrint('Cart: ${items.join(', ')}');
}

Because kDebugMode is a constant, the compiler removes the whole block from a release build, string and all. debugPrint is also a variable, so you can silence it in one place at startup:

if (kReleaseMode) {
debugPrint = (String? message, {int? wrapWidth}) {};
}

Notice what this does, though — the same thing R8 does on Android: the release build is quieter, so the lines that would explain a production bug don't exist anywhere. That's the right trade only while nobody can read them.

Flutter Remote Logging: a Package That Sends Logs to a Server​

Remote logging changes that trade. An SDK in your app collects the log lines and errors and uploads them, so you can read a user's session after they report a bug — on a device you've never touched. Those logs are worth keeping in release builds, at every level.

Full disclosure: I'm the founder of Shipbook, so here's how it works with ours. It runs on every platform Flutter builds for: Android, iOS, the web, macOS, Windows and Linux. Add shipbook_flutter to pubspec.yaml:

dependencies:
shipbook_flutter: ^2.1.0

Start it once in main:

import 'package:shipbook_flutter/shipbook_flutter.dart';

void main() {
runApp(const ShopApp());
Shipbook.start('YOUR_APP_ID', 'YOUR_APP_KEY');
}

Then log through a Shipbook logger, one per class or screen:

final log = Shipbook.getLogger('CheckoutPage');

log.i('Order $orderId submitted');
log.w('Payment retry ${attempt + 1} of 3');

try {
await payments.charge(order);
} catch (error, stackTrace) {
log.e('Payment failed', error, stackTrace);
}

Pass the caught error and its stack trace to log.e, and the console shows the line where the error was thrown, not the line that logged it. The lines still show in the console while you develop, and they're also uploaded and grouped by user and session in the Shipbook console. You don't need to write the error handlers above: Shipbook sets FlutterError.onError and PlatformDispatcher.instance.onError itself, with the stack trace and the log lines that led up to the error. If you've set your own handlers before it starts — for another crash reporter, say — Shipbook calls them too.

Two more lines connect the session to the rest of your system. Shipbook.registerUser(userId) ties it to the user who reported the bug. And if you add Shipbook.getSessionHeaders() to the requests your app makes to your own backend, the console links the app's session to the backend sessions those requests created:

await http.post(
Uri.parse('https://api.example.com/checkout'),
headers: {'Content-Type': 'application/json', ...Shipbook.getSessionHeaders()},
body: jsonEncode(cart),
);

You still decide what's sent, in the Shipbook console and without shipping a new build — see the configuration guide. Flutter remote logging with Shipbook shows what the console looks like, and the Flutter integration docs cover the full API.

Where Each Flutter Log Line Ends Up​

Every Flutter log line lands in one of five places. In DevTools, if you used dart:developer and a debugger was attached. In the terminal and the platform log of the device it ran on, if you used print or debugPrint — readable by flutter logs, adb, Xcode or the browser's DevTools, until newer lines push it out, and lost on a desktop app started from its icon. Nowhere, if it was a logger call in a release build, or a block behind kDebugMode. In a gray box, if it was an error during build. Or on a server, where you can read it next week for the one user whose checkout broke.

The first four come with Flutter or a package, and you should know all of them. Only the fifth helps with the bug you can't reproduce on your own device.

Shipbook is free to start, with up to 100,000 logs a day: create an account, add shipbook_flutter, and the next bug report from a user comes with the logs from their device.