Shield debugPrint and print output in Flutter/Dart release mode

When we are writing Flutter and Dart programs, in release mode, we find that the output content of debugPrint and print can still be displayed through flutter logs . This is especially the case when the problems exposed on the end are more serious, such as log printing involving some sensitive information.

In this article, there will be two super simple methods to achieve the shielding of these outputs, and they are designed to deal with problems in release mode, and debug mode is not affected.

DebugPrint

DebugPrint is really a confusing method. We understand that the log print is only performed in debug mode, but in fact, this method will also perform log output in release mode.

Fortunately, we can deal with the above problems with such a simple setting.

 1 2 3 4 5 
if ( kReleaseMode ) { debugPrint = ( String ? message , { int ? wrapWidth }) { // empty debugPrint implementation in the release mode }; }

Just before RunApp starts.

print processing

The processing of print is relatively troublesome, but the dart layer also provides a method to overload the print implementation, which is to use the Zone API.

The realization idea is as follows

  • Wrap runApp with runZonedGuarded
  • Add zoneSpecification parameter to configure printHandler
  • printHandler adds release mode control to perform log printing mask processing.

The specific code is as follows

 1 2 3 4 5 6 7 8 9 10 11 12 13 
runZonedGuarded (() { runApp ( MyApp ()); }, ( error , stackTrace ) { print ( stackTrace ); }, zoneSpecification: ZoneSpecification ( print: ( Zone self , ZoneDelegate parent , Zone zone , String message ){ /** * Print only in debug mode * */ if ( kDebugMode ) { parent . print ( zone , "wrapped content= $ message " ); } }));

other suggestions

  • Use your own encapsulated Log library for unified management
  • Use lint to inspect, detect and process code using print, debugPrint.

droidyue_gzh_green_png.png

This article is reprinted from https://droidyue.com/blog/2022/05/23/disable-debugprint-and-print-in-flutter-dart-release-mode/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment

Your email address will not be published.