You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Dart的Logger包禁用Flutter应用的所有日志?

禁用Flutter应用内所有日志的几种方法

针对你使用logger包的场景,结合生产环境需求,提供以下实用方案:

1. 针对logger包的环境化配置

通过自动识别运行环境,在生产环境下直接禁用日志输出:

late Logger logger;

void main() async {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
  await initializeDependencies();
  
  // dart.vm.product在release编译时自动为true
  const isProduction = bool.fromEnvironment('dart.vm.product');

  logger = Logger(
    // 生产环境用空打印机,不生成任何日志内容
    printer: isProduction ? NullPrinter() : PrettyPrinter(
        methodCount: 0,
        errorMethodCount: 0,
        lineLength: 150,
        colors: true,
        printEmojis: true),
    // 生产环境禁用控制台输出
    output: isProduction ? NullOutput() : ConsoleOutput(),
  );

  runApp(const MyApp());
}

2. 全局禁用所有日志输出

如果需要覆盖Flutter框架自带的print、debugPrint等日志方法,彻底关闭所有日志渠道:

void main() async {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  
  // 清空debugPrint的实现
  debugPrint = (String? message, {int? wrapWidth}) {};
  // 覆盖print方法为空操作
  print = (Object? object) {};

  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
  await initializeDependencies();
  
  const isProduction = bool.fromEnvironment('dart.vm.product');
  logger = Logger(
    printer: isProduction ? NullPrinter() : PrettyPrinter(...),
    output: isProduction ? NullOutput() : ConsoleOutput(),
  );

  runApp(const MyApp());
}

3. 编译期移除日志代码

借助assert特性,让生产环境下的日志代码直接被编译剔除,无任何性能开销:

// 封装自定义日志方法
void appLog(String message) {
  assert(() {
    logger.d(message);
    return true;
  }());
}

使用时直接调用appLog("日志内容"),release编译时这些日志代码会被完全移除。

内容的提问来源于stack exchange,提问作者Mona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 09:16:08