在Dart中禁用print()

时间:2018-04-25 19:20:46

标签: dart

有没有办法禁用打印功能Dart代码或以某种方式拦截它? 我们团队中的一些开发人员继续使用print而不是我们构建的logger,这意味着我们在控制台中看到很多垃圾,我们无法关闭,除非我们通过所有代码进行搜索替换以查找 并将print(String)替换为log.info(String)

理想情况下,我们应该使用预提交钩子来检查提交的代码是否包含打印,然后拒绝提交,但是在代码级别阻止打印似乎更快。

// 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);
  }
}

printdart.core的一部分,是否可以通过代码或dart.core中的某个转换器覆盖pubspec.yaml中的任何内容?

如果没有,我想是时候设置提前挂钩了。

1 个答案:

答案 0 :(得分:6)

我认为最好的解决方案是像https://github.com/dart-lang/linter/issues/88

这样的linter规则

与此同时,您可以在新区域中运行代码并覆盖那里的打印方法

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');
    })
  );
}