8.3 日志与调试
完善的日志体系和错误上报机制是生产级 App 的必备能力有助于快速定位线上问题。一、logger 包dependencies:logger:^2.3.0importpackage:logger/logger.dart;classAppLogger{staticfinalLogger_loggerLogger(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.dartFuturevoidmain()async{awaitSentryFlutter.init((options){options.dsnAppConfig.sentryDsn;options.environmentAppConfig.appEnv;options.releasemy_app1.0.01;options.tracesSampleRate0.2;// 20% 性能追踪options.profilesSampleRate0.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()));},);}// 性能追踪FuturevoidloadProductList()async{finaltransactionSentry.startTransaction(loadProductList,http.client);try{finalproductsawaitrepository.fetchAll();transaction.statusconstSpanStatus.ok();returnproducts;}catch(e){transaction.statusconstSpanStatus.internalError();rethrow;}finally{awaittransaction.finish();}}三、全局异常捕获Futurevoidmain()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 模式importdart:developer;debugger(when:condition,message:Break here);// inspect()在 DevTools Inspector 中查看对象inspect(myObject);小结工具用途logger分级日志开发调试Sentry生产错误上报性能追踪FlutterError.onError捕获 Flutter 框架错误PlatformDispatcher.onError捕获未处理的 Dart 异步错误 下一章九、平台交互Platform Integration