Last active
April 1, 2020 23:37
-
-
Save filiph/360610c60cbde083eacdb1947057f517 to your computer and use it in GitHub Desktop.
Using runZoned to catch print() logs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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