news 2026/4/15 4:18:39

8.3 日志与调试

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
8.3 日志与调试

完善的日志体系和错误上报机制是生产级 App 的必备能力,有助于快速定位线上问题。


一、logger 包

dependencies:logger:^2.3.0
import'package:logger/logger.dart';classAppLogger{staticfinalLogger_logger=Logger(printer:PrettyPrinter(methodCount:2,// 显示 2 层调用栈errorMethodCount:8,// 错误时显示 8 层调用栈lineLength:120,colors:true,printEmojis:true,dateTimeFormat:DateTimeFormat.onlyTimeAndSinceStart,),filter:ProductionFilter(),// 生产环境过滤 debug 日志level:AppConfig.isDevelopment?Level.trace:Level.warning,);staticvoidtrace(dynamicmessage,[Object?error,StackTrace?stackTrace])=>_logger.t(message,error:error,stackTrace:stackTrace);staticvoiddebug(dynamicmessage,[Object?error,StackTrace?stackTrace])=>_logger.d(message,error:error,stackTrace:stackTrace);staticvoidinfo(dynamicmessage,[Object?error,StackTrace?stackTrace])=>_logger.i(message,error:error,stackTrace:stackTrace);staticvoidwarning(dynamicmessage,[Object?error,StackTrace?stackTrace])=>_logger.w(message,error:error,stackTrace:stackTrace);staticvoiderror(dynamicmessage,[Object?error,StackTrace?stackTrace])=>_logger.e(message,error:error,stackTrace:stackTrace);staticvoidfatal(dynamicmessage,[Object?error,StackTrace?stackTrace])=>_logger.f(message,error:error,stackTrace:stackTrace);}// 使用AppLogger.info('用户登录成功:${user.name}');AppLogger.error('API 请求失败',e,stackTrace);

二、Sentry 错误上报

dependencies:sentry_flutter:^7.19.0
// main.dartFuture<void>main()async{awaitSentryFlutter.init((options){options.dsn=AppConfig.sentryDsn;options.environment=AppConfig.appEnv;options.release='my_app@1.0.0+1';options.tracesSampleRate=0.2;// 20% 性能追踪options.profilesSampleRate=0.1;// 过滤不需要上报的错误options.beforeSend=(event,hint){if(event.throwableisNetworkException)returnnull;// 不上报网络错误returnevent;};},appRunner:()=>runApp(constMyApp()),);}// 手动上报try{awaitriskyOperation();}catch(e,stackTrace){awaitSentry.captureException(e,stackTrace:stackTrace);// 或附加额外信息awaitSentry.captureException(e,stackTrace:stackTrace,withScope:(scope){scope.setTag('operation','checkout');scope.setExtra('orderId',orderId);scope.setUser(SentryUser(id:currentUser.id.toString()));},);}// 性能追踪Future<void>loadProductList()async{finaltransaction=Sentry.startTransaction('loadProductList','http.client');try{finalproducts=awaitrepository.fetchAll();transaction.status=constSpanStatus.ok();returnproducts;}catch(e){transaction.status=constSpanStatus.internalError();rethrow;}finally{awaittransaction.finish();}}

三、全局异常捕获

Future<void>main()async{// 捕获 Flutter 框架内的错误FlutterError.onError=(details){AppLogger.error('Flutter Error:${details.exception}',details.exception,details.stack,);Sentry.captureException(details.exception,stackTrace:details.stack);};// 捕获 Dart 异步错误(未被 try-catch 捕获的)PlatformDispatcher.instance.onError=(error,stack){AppLogger.fatal('Uncaught Error:$error',error,stack);Sentry.captureException(error,stackTrace:stack);returntrue;// 返回 true 表示已处理};// 确保 Flutter 绑定初始化完成后再捕获错误runApp(constProviderScope(child:MyApp()),);}

四、调试技巧

// 仅在 Debug 模式下执行assert((){print('Debug only:$data');returntrue;}());// kDebugMode / kReleaseMode / kProfileModeif(kDebugMode){print('Debug mode log');}// debugger():在代码中设置断点(需 Debug 模式)import'dart:developer';debugger(when:condition,message:'Break here');// inspect():在 DevTools Inspector 中查看对象inspect(myObject);

小结

工具用途
logger分级日志,开发调试
Sentry生产错误上报,性能追踪
FlutterError.onError捕获 Flutter 框架错误
PlatformDispatcher.onError捕获未处理的 Dart 异步错误

👉 下一章:九、平台交互(Platform Integration)

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/15 4:15:18

终极Siren使用指南:从基础集成到高级更新策略全解析

终极Siren使用指南&#xff1a;从基础集成到高级更新策略全解析 【免费下载链接】Siren Notify users when a new version of your app is available and prompt them to upgrade. 项目地址: https://gitcode.com/gh_mirrors/si/Siren Siren是一款功能强大的iOS应用更新…

作者头像 李华
网站建设 2026/4/15 4:15:17

HCPL-1931,双通道1000V/µs高速TTL兼容气密封装光耦合器

简介 今天我要向大家介绍的是 Broadcom 的光耦合器——HCPL-1931。它是一款双通道、兼容 TTL 逻辑的高速线路接收器光耦合器。该器件内部采用 GaAsP LED 技术&#xff0c;并集成了输入电流调节器&#xff0c;可作为线路端接&#xff0c;钳位线路电压并调节LED电流&#xff0c;防…

作者头像 李华
网站建设 2026/4/15 4:14:45

VisualVM实战指南:从插件安装到远程JVM监控

1. VisualVM入门&#xff1a;你的JVM性能分析利器 第一次听说VisualVM时&#xff0c;我也和大多数Java开发者一样疑惑&#xff1a;这工具到底能干什么&#xff1f;简单来说&#xff0c;它就是JVM的"体检中心"&#xff0c;能实时查看内存泄漏、线程死锁、CPU过载等问题…

作者头像 李华
网站建设 2026/4/15 4:10:15

macOS 彻底卸载 Python 的完整指南

macOS 彻底卸载 Python 的完整指南摘要⚠️ 重要警告&#x1f50d; 卸载前检查&#x1f5d1;️ 卸载方法&#xff08;按安装方式&#xff09;1. 卸载 Homebrew 安装的 Python2. 卸载官方 pkg 安装的 Python3. 卸载 pyenv 管理的 Python4. 卸载 Miniconda/Anaconda&#x1f9f9;…

作者头像 李华