Flutter日志工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

// 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);
}

Fred范方青 wechat
项目合作请联系我私人微信: fredtv23
0%