Sub topic 5
Logging with dart:developer and the Logging view
This chapter assumes you can run a Flutter app on a device or emulator and that you have DevTools open and connected, as covered in the first chapters. It also assumes you know basic Dart try/catch and async code. Here you will learn how to write log messages that are easy to find in DevTools and how to read them in the Logging view.
Why logging still matters
A breakpoint stops the app so you can look at one moment. A log message records many moments without stopping anything. That makes logs the better tool when:
- The bug depends on timing, such as a race between two requests.
- The bug appears only after a long sequence of user actions.
- You need to see the order of events, not the state at one instant.
- Pausing the app would change the behavior you are trying to observe, for example during an animation.
The usual first reflex is print. It works, but it gives you one undifferentiated stream of text. dart:developer gives each message a name, a severity level, and optional error and stack trace data. DevTools can then filter on those fields.
print, debugPrint, and developer.log
Flutter offers three common ways to write a message. They differ in where the text goes and how much structure it carries.
| Function | Output goes to | Structure | Typical use |
|---|---|---|---|
| `print` | Standard output (the `flutter run` console, Logcat, the Logging view) | Text only | Quick throwaway checks |
| `debugPrint` | Standard output, throttled | Text only | Large or rapid output on Android |
| `developer.log` | The Dart VM service, shown in the Logging view | Name, level, error, stack trace, time | Messages you want to filter and keep |
Two details explain why debugPrint exists. On Android, the system log can drop lines when an app prints too much too quickly. debugPrint throttles its output to avoid that. Separately, long single lines may be truncated by the platform log. developer.log is not subject to these limits for the Logging view, because it sends messages through the VM service rather than through standard output.
The developer.log function
log lives in dart:developer. Because that library also exports names such as Timeline and debugger, import it with a prefix to keep your code readable.
import 'dart:developer' as developer;
void loadCart(List<String> items) {
developer.log(
'Loaded ${items.length} items',
name: 'cart',
);
}The function has one required positional argument and several named ones:
messageis the text.nameidentifies the source. By convention it is a short, lowercase area such ascart,auth, orhttp. Use the same name consistently so you can filter on it.levelis an integer severity. The default is0.erroris any object, usually the caught exception.stackTraceis the trace that goes with the error.time,sequenceNumber, andzoneare available but rarely set by hand.
Choosing level values
The level value is just an integer. Dart does not define named constants for it in dart:developer. The common convention comes from package:logging, so your numbers line up if you adopt that package later.
| Level name | Value | Meaning |
|---|---|---|
| FINE | 500 | Detailed tracing |
| INFO | 800 | Normal events worth recording |
| WARNING | 900 | Something odd, but the app continued |
| SEVERE | 1000 | A failure |
Define these once so that call sites read clearly.
import 'dart:developer' as developer;
const int levelFine = 500;
const int levelInfo = 800;
const int levelWarning = 900;
const int levelSevere = 1000;
int parseQuantity(String raw) {
developer.log('Parsing "$raw"', name: 'cart', level: levelFine);
try {
final value = int.parse(raw);
if (value > 99) {
developer.log(
'Quantity $value is unusually large',
name: 'cart',
level: levelWarning,
);
}
return value;
} on FormatException catch (e, st) {
developer.log(
'Could not parse quantity',
name: 'cart',
level: levelSevere,
error: e,
stackTrace: st,
);
return 1;
}
}
void main() {
parseQuantity('3');
parseQuantity('250');
parseQuantity('abc');
}Passing error and stackTrace as separate arguments matters. If you interpolate the exception into the message string, you lose the structured fields, and DevTools cannot show the trace as a trace.
Opening the Logging view
In DevTools, select the Logging tab. If the tab is missing, the app is probably not connected, so check the connection from the first chapter. The view is a table that fills from the top as events arrive. Each row shows a kind label on the left and the message text. Selecting a row shows its details in a pane below the table, including the error and stack trace if you supplied them.
The Logging view does not show only your own messages. It merges several sources into one timeline.
The framework events include frame timing notes, garbage collection, and navigation changes. They are useful context, but they can bury your own messages. This is the main reason to give your messages a name.
Filtering and searching
A busy app can produce hundreds of rows per second. The Logging view gives you a filter field above the table. Type text to show only rows that contain it, and use the filter options to narrow by kind or by minimum level. The exact controls vary a little between DevTools releases, so check the filter button in your version.
A practical approach:
- Pick a
namefor the area you are debugging, for examplecart. - Type that name into the filter.
- Reproduce the bug.
- Read the rows in order, and select the suspicious one to see its detail pane.
Use Clear before each reproduction. A clean table makes it obvious which rows belong to the attempt you just made.
A complete example
This app logs a button press, a simulated slow request, and a failure. Run it, open the Logging view, and filter on checkout.
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: CheckoutPage()));
class CheckoutPage extends StatefulWidget {
const CheckoutPage({super.key});
@override
State<CheckoutPage> createState() => _CheckoutPageState();
}
class _CheckoutPageState extends State<CheckoutPage> {
String _status = 'Idle';
Future<void> _pay() async {
developer.log('Pay pressed', name: 'checkout', level: 800);
setState(() => _status = 'Paying...');
try {
await Future<void>.delayed(const Duration(milliseconds: 500));
throw StateError('Card declined');
} catch (e, st) {
developer.log(
'Payment failed',
name: 'checkout',
level: 1000,
error: e,
stackTrace: st,
);
if (!mounted) return;
setState(() => _status = 'Failed');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_status),
ElevatedButton(onPressed: _pay, child: const Text('Pay')),
],
),
),
);
}
}After one press you should see two rows named checkout: an informational row and a severe row. Select the severe row to see the StateError and the stack trace that points into _pay.
Logging only when it helps
Log calls cost a little time, and string interpolation runs even if nobody is reading the result. Two habits keep this under control.
First, guard expensive messages with kDebugMode from package:flutter/foundation.dart. This constant is true only in debug mode, and the compiler can remove the guarded code from release builds.
import 'dart:developer' as developer;
import 'package:flutter/foundation.dart';
void logLargePayload(List<Map<String, Object?>> rows) {
if (kDebugMode) {
developer.log(
'Rows: ${rows.map((r) => r.toString()).join('; ')}',
name: 'sync',
level: 500,
);
}
}Second, do not log inside build unless you are specifically counting rebuilds. build can run many times per second, and the flood of rows will hide everything else.
Common errors
- Messages do not appear. Check that the app is connected and that the Logging tab is selected. Then check that no filter is active. A leftover filter from an earlier session is the most common cause.
- Messages appear but the error detail is empty. You passed the exception inside the message text instead of through
error:. - Everything is at level 0. You forgot the
levelargument, so severity filtering cannot separate routine messages from failures. - The table is full of framework rows. Filter on your
name, and clear the table before reproducing. - Output is cut off or missing on Android with
print. Switch todebugPrintordeveloper.log. - Logs from a background isolate seem to be missing. Confirm that DevTools is attached to the isolate that runs the code. Isolates are separate execution contexts, and the isolate selector in DevTools controls which one you are inspecting. If your version does not show logs from other isolates, log a summary on the main isolate instead.
When to switch to another tool
Logging answers "what happened, and in what order?" It does not answer "what is the value of every variable right now?" (use a breakpoint, covered in the next chapter) or "why is this frame slow?" (use the Performance view). If you find yourself adding a log line for every variable in a function, that is the signal to set a breakpoint instead.
Exercise
A teammate writes developer.log('Failed: $e') inside a catch (e, st) block. In the Logging view, the row has no stack trace in its detail pane, and filtering for severe messages finds nothing. List the two changes that fix both problems.
Show answer
Pass the exception and trace as structured arguments, error: e and stackTrace: st, so the detail pane can show them. Also set level: 1000 (SEVERE by the package:logging convention) so level filtering can find the row. Adding a consistent name, such as name: 'cart', makes the row easy to filter by area as well.
Exercise
Why is it better to guard a log call that builds a very large string with if (kDebugMode) than to rely on the Logging view being unavailable in release mode?
Show answer
The string is still built whenever the log call runs, even if no one can read it, and that wastes CPU time and memory. The kDebugMode guard stops the work from happening at all, and the compiler can remove the guarded code from release builds.