Skip to content

Instantly share code, notes, and snippets.

@filiph
Last active April 1, 2020 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filiph/360610c60cbde083eacdb1947057f517 to your computer and use it in GitHub Desktop.
Save filiph/360610c60cbde083eacdb1947057f517 to your computer and use it in GitHub Desktop.
Using runZoned to catch print() logs
import 'dart:async';
/// This service logs via [print]. Ugh.
void runMisbehavingService() async {
print('Starting service...');
await Future.delayed(const Duration(milliseconds: 100));
print('... started.');
}
void main() async {
var logMessages = <String>[];
// We're running the service in its own Zone.
runZoned(
() => runMisbehavingService(),
// Here, we can give options to the new Zone.
zoneSpecification: ZoneSpecification(
// For example, we can overload the `print` statement.
print: (self, parent, zone, line) => logMessages.add(line),
),
);
print('Service generated ${logMessages.length} log(s) so far: $logMessages');
await Future.delayed(const Duration(seconds: 1));
print('Service generated ${logMessages.length} log(s) so far: $logMessages');
// Note how the Zone keeps working even with asynchronous code.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment