I use log
from import 'dart:developer';
but it seems that it does not print anything when I use from unit test.
What should I use for logging in both test and dev environments but not in production?
Thanks.
I use log
from import 'dart:developer';
but it seems that it does not print anything when I use from unit test.
What should I use for logging in both test and dev environments but not in production?
Thanks.
dart:developer
only works in debug environments where the Dart vm service is available. As such, launching the unit tests with the debugger attached should work fine. It programmatically interacts with the Dart VM and debugger, so if those aren't attached it won't work properly.
However, logging can be very helpful for production environments as well, so I’d recommend migrating to a different package for a robust logging service across environments. dart:developer
is not designed as a logger.
Messages sent through dart:developer
log() will be handled via the Dart VM's native code implementation, note the external
function definition in the src code. Tools such as the Flutter Devtools are then free to subscribe to receiving and displaying these messages.
In Flutter apps, the logging will be sent to usual app console output, however if you are using this for a Dart command line application or want output when running unit tests for Flutter apps, you should be able to see that via IDE's, in theory both the VSCode and IntelliJ Dart/Flutter plugins have explicit support added to them to display the output for log()
, though currently in the case of DartCode there maybe a bug preventing that.
In theory you can also add support using the Dart vm_service
package to read the log messages and send the to stdout/stderr yourself when running unit tests, but in this case it may just be easier to switch to using the logging
package published by the Dart team and then you'll likely want to enable explicitly send the output to stdout and/or stderr in the Logger's listen()
callback:
// pass true to enable output to stderr
Logger.root.onRecord.listen((LogRecord rec) {
final mesg = '${rec.level.name}: ${rec.time}: ${rec.message}';
if (true == useStd) {
if (rec.level >= Level.SEVERE) {
stderr.writeln('$mesg\n${rec.error}\n${rec.stackTrace}');
} else {
stdout.writeln(mesg);
}
} else {
developer.log(mesg, level: rec.level.value, error: rec.error);
}
});