Flutter日志工具类 发表于 2021-11-17 | 分类于 dev 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475// flog.dart// ilog("msg info"); 调用方式import 'package:flutter/foundation.dart';import 'package:stack_trace/stack_trace.dart';const String _tag = "fred_";const bool _logOpen = true;enum FLogMode { debug, // 💚 DEBUG warning, // 💛 WARNING info, // 💙 INFO error, // ❤️ ERROR}void _log(dynamic msg, FLogMode mode){ if (kReleaseMode || _logOpen == false) { // release 模式不打印 return; } var chain = Chain.current(); // Chain.forTrace(StackTrace.current); // 将 core 和 flutter 包的堆栈合起来(即相关数据只剩其中一条) chain = chain.foldFrames((frame) => frame.isCore || frame.package == "flutter"); // 取出所有信息帧 final frames = chain.toTrace().frames; // 找到当前函数的信息帧 final idx; var modeStr = ""; switch(mode) { case FLogMode.debug: modeStr = "💚 DEBUG"; idx = frames.indexWhere((element) => element.member == "dlog"); break; case FLogMode.warning: modeStr = "💛 WARNING"; idx = frames.indexWhere((element) => element.member == "wlog"); break; case FLogMode.info: modeStr = "💙 INFO"; idx = frames.indexWhere((element) => element.member == "ilog"); break; case FLogMode.error: modeStr = "❤️ ERROR"; idx = frames.indexWhere((element) => element.member == "elog"); break; } if (idx == -1 || idx+1 >= frames.length) { return; } // 调用当前函数的函数信息帧 final frame = frames[idx+1]; print("$_tag${frame.uri.toString().split("/").last}(${frame.line}) :: $modeStr - $msg ");}void dlog(dynamic msg, { FLogMode mode = FLogMode.debug }) { _log(msg, mode);}void elog(dynamic msg, { FLogMode mode = FLogMode.error }) { _log(msg, mode);}void ilog(dynamic msg, { FLogMode mode = FLogMode.info }) { _log(msg, mode);}void wlog(dynamic msg, { FLogMode mode = FLogMode.warning }) { _log(msg, mode);} 项目合作请联系我私人微信: fredtv23 本文作者: Fred范方青 本文链接: https://blog.fanfq.com/dev/flutter_logs_utils.html 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!