dart - 在 Dart 中禁用 print()
问题描述
有没有办法禁用打印功能 Dart 代码或以某种方式拦截它?print(String)
我们团队中的一些开发人员继续使用 print 而不是我们构建的记录器,这意味着我们在控制台中看到很多垃圾,除非我们对所有代码进行搜索替换以查找和替换,否则我们无法关闭这些垃圾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);
}
}
print
是的一部分,是否可以通过代码或通过某些转换dart.core
器覆盖任何内容?dart.core
pubspec.yaml
如果没有,我想是时候设置预提交挂钩了。
解决方案
我认为最好的解决方案是像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'); }) ); }
并在发布模式下隐藏打印
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);
}
}));
}
推荐阅读
- r - 将 API 响应从 JSON 转换为 R Data DataFrame
- excel - 在 Excel 中更新多个图表
- ios - 客户端应用程序错误 - UITargetedPreview 的视图或容器当前都不在窗口中
- powershell - Powershell删除包含多个文本文件的文件夹中的重复行
- javascript - 为什么这个被注释掉的函数不能达到与它下面的 if 语句相同的结果?我怎样才能让它发挥作用?
- c++ - 当您首先将名称存储在变量中时,您如何命名一个类?
- c# - 使用 IEnumerator 和使用数组作为属性之间的区别
- r - 使用 ggplot2 通过 Map 绘制密度图
- ruby-on-rails - 每当 Rails 中用于 cron 的 gem 无法在 Mac 中运行并且找不到日志时
- python - 如何评估具有可变内积分上限的双积分