在Dart中禁用print()

扬·弗拉基米尔·莫斯特尔

有没有办法禁用打印功能Dart代码或以某种方式截获它?使用的,而不是我们建立的记录,这意味着我们看到了很多垃圾在控制台中,我们没有关掉的方式,除非我们通过做所有的代码搜索替换查找和替换打印对我们的团队保留一些开发者print(String)log.info(String)

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

// 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是的一部分dart.core,是否dart.core可以通过代码或通过某些转换器覆盖中的任何内容pubspec.yaml

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

贡特·佐赫鲍尔(GünterZöchbauer)

我认为最好的解决方案将是像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');
    })
  );
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章