1. Install package logging

Add logging to pubspec.yaml file:

pubspec.yaml
1
2
dependencies:
logging: ^0.11.4

2. Config Logger

Initialize Logger before runApp() in main.dart file:

main.dart
1
2
3
4
5
6
7
8
9
import 'logging.dart';
void main() {
// config logger before runApp()
initLogging();
runApp(MyApp());

// log a debug message
log.fine('Running my flutter app.');
}
logging.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import 'package:logging/logging.dart';

// create Logger by name 'MyApp'
final log = Logger('MyApp');
void initLogging() {
// disable hierarchical logger
hierarchicalLoggingEnabled = false;
// change to another level as needed.
Logger.root.level = Level.INFO;
// skip logging stactrace below the SEVERE level.
recordStackTraceAtLevel = Level.SEVERE;
assert(() {
recordStackTraceAtLevel = Level.WARNING;
// print all logs on debug build.
Logger.root.level = Level.ALL;
return true;
}());
}

3. Transmit log records from Logger to dart:developer

Logger is a producer, but it will not post any log records if no one is listening.

Print to console:

logging.dart
1
2
3
Logger.root.onRecord.listen((event) {
print("${event.time}: [${event.level}] [${event.loggerName}] ${event.message}");
});

Save to file:

logging.dart
1
2
3
4
5
File logFile = ...
Logger.root.onRecord.listen((event) {
logFile.writeAsString("${event.time}: [${event.level}] [${event.loggerName}] ${event.message}",
mode: FileMode.append);
});

It’s strongly recommended to use dart:developer for logging:

logging.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import 'dart:developer' as developer;

void initLogging() {
...
Logger.root.onRecord.listen((event) {
developer.log(
event.message,
time: event.time,
sequenceNumber: event.sequenceNumber,
level: event.level.value,
name: event.loggerName,
zone: event.zone,
error: event.error,
stackTrace: event.stackTrace,
);
});
}

4. Example

Logging a debug message on track():

1
2
3
4
5
6
7
8
9
import 'package:logging/logging.dart';
class EventReporter {
// create Logger for this class
final log = Logger('comic.report');
void track(String event, [Map<String, dynamic> arguments]) {
...
log.fine('track event $event args: $arguments');
}
}

If using dart:developer for consuming log records, please check the following.

Flutter console displays logs:
screenshots

DevTools’ Logging view shows logs:
screenshots

Complete code

See gist: https://gist.github.com/yrom/1a86a6995720d9a4ff9261617fb13783

Redirect ‘print’

main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void main() {
runZoned((){
runApp(MyApp());
}, zoneSpecification: ZoneSpecification(print: printToDeveloper));
}
/// see [PrintHandler]
void printToDeveloper(Zone self, ZoneDelegate parent, Zone zone, String line) {
developer.log(
line,
time: DateTime.now(),
level: Level.FINE.value,
name: 'console',
zone: zone,
);
// if you need print to console
// Zone.root.print(line);
}

References