Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable print() in Dart

Tags:

dart

Is there a way to disable the print function Dart code or somehow intercept it? Some devs on our team keep on using print instead of the logger we built which means we see a lot of garbage in the console that we have no way of switching off unless we do a search replace through all the code to find and replace print(String) with log.info(String)

Ideally we should be using a pre-commit hook to check if the committed code contains prints and then reject the commit, but it seems quicker to just block the print at code-level.

// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

part of dart.core;

/// Prints a string representation of the object to the console.
void print(Object object) {
  String line = "$object";
  if (printToZone == null) {
    printToConsole(line);
  } else {
    printToZone(line);
  }
}

print is part of dart.core, is it possible to override anything in dart.core either via code or via some transformer in pubspec.yaml?

If not, I guess it's time to go setup that pre-commit hook.

like image 678
Jan Vladimir Mostert Avatar asked Dec 23 '22 07:12

Jan Vladimir Mostert


1 Answers

I think the best solution will be a linter rule like https://github.com/dart-lang/linter/issues/88

In the meantime you can run code in a new zone and override the print method there

https://api.dartlang.org/stable/1.24.3/dart-async/ZoneSpecification-class.html

https://api.dartlang.org/stable/1.24.3/dart-async/Zone/print.html

https://api.dartlang.org/stable/1.24.3/dart-async/PrintHandler.html

http://jpryan.me/dartbyexample/examples/zones/

import 'dart:async';

main() {
  // All Dart programs implicitly run in a root zone.
  // runZoned creates a new zone.  The new zone is a child of the root zone.
  runZoned(() async {
    await runServer();
  },
  // Any uncaught errors in the child zone are sent to the [onError] handler.
      onError: (e, stacktrace) {
    print('caught: $e');
  },
  // a ZoneSpecification allows for overriding functionality, like print()
    zoneSpecification: new ZoneSpecification(print: (Zone self, ZoneDelegate parent, Zone zone, String message) {
      parent.print(zone, '${new DateTime.now()}: $message');
    })
  );
}

And to hide print in release mode

main() {
   runZonedGuarded(() {
   runApp(MyApp());
 }, (error, stackTrace) {
   print(stackTrace);
 }, zoneSpecification: new ZoneSpecification(
     print: (Zone self, ZoneDelegate parent, Zone zone, String message){
   // parent.print(zone, '${new DateTime.now()}: $message');
   /**
    * Print only in debug mode
    * */
   if (kDebugMode) {
     parent.print(zone, message);
   }
 }));
}
like image 69
Günter Zöchbauer Avatar answered Jan 31 '23 19:01

Günter Zöchbauer