-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathpretty_printer.dart
More file actions
318 lines (275 loc) · 9.09 KB
/
pretty_printer.dart
File metadata and controls
318 lines (275 loc) · 9.09 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import 'dart:convert';
import 'package:logger/src/logger.dart';
import 'package:logger/src/log_printer.dart';
import 'package:logger/src/ansi_color.dart';
/// Default implementation of [LogPrinter].
///
/// Output looks like this:
/// ```
/// ┌──────────────────────────
/// │ Error info
/// ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
/// │ Method stack history
/// ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
/// │ Log message
/// └──────────────────────────
/// ```
class PrettyPrinter extends LogPrinter {
static const topLeftCorner = '┌';
static const bottomLeftCorner = '└';
static const middleCorner = '├';
static const verticalLine = '│';
static const doubleDivider = '─';
static const singleDivider = '┄';
static final levelColors = {
Level.verbose: AnsiColor.fg(AnsiColor.grey(0.5)),
Level.debug: AnsiColor.none(),
Level.info: AnsiColor.fg(12),
Level.warning: AnsiColor.fg(208),
Level.error: AnsiColor.fg(196),
Level.wtf: AnsiColor.fg(199),
};
static final levelEmojis = {
Level.verbose: '',
Level.debug: '🐛 ',
Level.info: '💡 ',
Level.warning: '⚠️ ',
Level.error: '⛔ ',
Level.wtf: '👾 ',
};
/// Matches a stacktrace line as generated on Android/iOS devices.
/// For example:
/// #1 Logger.log (package:logger/src/logger.dart:115:29)
static final _deviceStackTraceRegex =
RegExp(r'#[0-9]+[\s]+(.+) \(([^\s]+)\)');
/// Matches a stacktrace line as generated by Flutter web.
/// For example:
/// packages/logger/src/printers/pretty_printer.dart 91:37
static final _webStackTraceRegex =
RegExp(r'^((packages|dart-sdk)\/[^\s]+\/)');
/// Matches a stacktrace line as generated by browser Dart.
/// For example:
/// dart:sdk_internal
/// package:logger/src/logger.dart
static final _browserStackTraceRegex =
RegExp(r'^(?:package:)?(dart:[^\s]+|[^\s]+)');
static DateTime? _startTime;
/// The index which to begin the stack trace at
///
/// This can be useful if, for instance, Logger is wrapped in another class and
/// you wish to remove these wrapped calls from stack trace
final int stackTraceBeginIndex;
final int methodCount;
final int errorMethodCount;
final int lineLength;
final bool colors;
final bool printEmojis;
final bool printTime;
/// To prevent ascii 'boxing' of any log [Level] include the level in map for excludeBox,
/// for example to prevent boxing of [Level.verbose] and [Level.info] use excludeBox:{Level.verbose:true, Level.info:true}
final Map<Level, bool> excludeBox;
/// To make the default for every level to prevent boxing entirely set [noBoxingByDefault] to true
/// (boxing can still be turned on for some levels by using something like excludeBox:{Level.error:false} )
final bool noBoxingByDefault;
late final Map<Level, bool> includeBox;
String _topBorder = '';
String _middleBorder = '';
String _bottomBorder = '';
PrettyPrinter({
this.stackTraceBeginIndex = 0,
this.methodCount = 2,
this.errorMethodCount = 8,
this.lineLength = 120,
this.colors = true,
this.printEmojis = true,
this.printTime = false,
this.excludeBox = const {},
this.noBoxingByDefault = false,
}) {
_startTime ??= DateTime.now();
var doubleDividerLine = StringBuffer();
var singleDividerLine = StringBuffer();
for (var i = 0; i < lineLength - 1; i++) {
doubleDividerLine.write(doubleDivider);
singleDividerLine.write(singleDivider);
}
_topBorder = '$topLeftCorner$doubleDividerLine';
_middleBorder = '$middleCorner$singleDividerLine';
_bottomBorder = '$bottomLeftCorner$doubleDividerLine';
// Translate excludeBox map (constant if default) to includeBox map with all Level enum possibilities
includeBox = {};
Level.values.forEach((l) => includeBox[l] = !noBoxingByDefault);
excludeBox.forEach((k, v) => includeBox[k] = !v);
}
@override
List<String> log(LogEvent event) {
var messageStr = stringifyMessage(event.message);
String? stackTraceStr;
if (event.stackTrace == null) {
if (methodCount > 0) {
stackTraceStr = formatStackTrace(StackTrace.current, methodCount);
}
} else if (errorMethodCount > 0) {
stackTraceStr = formatStackTrace(event.stackTrace, errorMethodCount);
}
var errorStr = event.error?.toString();
String? timeStr;
if (printTime) {
timeStr = getTime();
}
return _formatAndPrint(
event.level,
messageStr,
timeStr,
errorStr,
stackTraceStr,
);
}
String? formatStackTrace(StackTrace? stackTrace, int methodCount) {
var lines = stackTrace.toString().split('\n');
var formatted = <String>[];
var count = 0;
for (var line in lines) {
if (_discardDeviceStacktraceLine(line) ||
_discardWebStacktraceLine(line) ||
_discardBrowserStacktraceLine(line) ||
line.isEmpty) {
continue;
}
if(count < stackTraceBeginIndex) {
count++;
continue;
}
formatted.add('#$count ${line.replaceFirst(RegExp(r'#\d+\s+'), '')}');
if (++count == methodCount) {
break;
}
}
if (formatted.isEmpty) {
return null;
} else {
return formatted.join('\n');
}
}
bool _discardDeviceStacktraceLine(String line) {
var match = _deviceStackTraceRegex.matchAsPrefix(line);
if (match == null) {
return false;
}
return match.group(2)!.startsWith('package:logger');
}
bool _discardWebStacktraceLine(String line) {
var match = _webStackTraceRegex.matchAsPrefix(line);
if (match == null) {
return false;
}
return match.group(1)!.startsWith('packages/logger') ||
match.group(1)!.startsWith('dart-sdk/lib');
}
bool _discardBrowserStacktraceLine(String line) {
var match = _browserStackTraceRegex.matchAsPrefix(line);
if (match == null) {
return false;
}
return match.group(1)!.startsWith('package:logger') ||
match.group(1)!.startsWith('dart:');
}
String getTime() {
String _threeDigits(int n) {
if (n >= 100) return '$n';
if (n >= 10) return '0$n';
return '00$n';
}
String _twoDigits(int n) {
if (n >= 10) return '$n';
return '0$n';
}
var now = DateTime.now();
var h = _twoDigits(now.hour);
var min = _twoDigits(now.minute);
var sec = _twoDigits(now.second);
var ms = _threeDigits(now.millisecond);
var timeSinceStart = now.difference(_startTime!).toString();
return '$h:$min:$sec.$ms (+$timeSinceStart)';
}
// Handles any object that is causing JsonEncoder() problems
Object toEncodableFallback(dynamic object) {
return object.toString();
}
String stringifyMessage(dynamic message) {
final finalMessage = message is Function ? message() : message;
if (finalMessage is Map || finalMessage is Iterable) {
var encoder = JsonEncoder.withIndent(' ', toEncodableFallback);
return encoder.convert(finalMessage);
} else {
return finalMessage.toString();
}
}
AnsiColor _getLevelColor(Level level) {
if (colors) {
return levelColors[level]!;
} else {
return AnsiColor.none();
}
}
AnsiColor _getErrorColor(Level level) {
if (colors) {
if (level == Level.wtf) {
return levelColors[Level.wtf]!.toBg();
} else {
return levelColors[Level.error]!.toBg();
}
} else {
return AnsiColor.none();
}
}
String _getEmoji(Level level) {
if (printEmojis) {
return levelEmojis[level]!;
} else {
return '';
}
}
List<String> _formatAndPrint(
Level level,
String message,
String? time,
String? error,
String? stacktrace,
) {
// This code is non trivial and a type annotation here helps understanding.
// ignore: omit_local_variable_types
List<String> buffer = [];
var verticalLineAtLevel = (includeBox[level]!) ? (verticalLine + ' ') : '';
var color = _getLevelColor(level);
if (includeBox[level]!) buffer.add(color(_topBorder));
if (error != null) {
var errorColor = _getErrorColor(level);
for (var line in error.split('\n')) {
buffer.add(
color(verticalLineAtLevel) +
errorColor.resetForeground +
errorColor(line) +
errorColor.resetBackground,
);
}
if (includeBox[level]!) buffer.add(color(_middleBorder));
}
if (stacktrace != null) {
for (var line in stacktrace.split('\n')) {
buffer.add(color('$verticalLineAtLevel$line'));
}
if (includeBox[level]!) buffer.add(color(_middleBorder));
}
if (time != null) {
buffer.add(color('$verticalLineAtLevel$time'));
if (includeBox[level]!) buffer.add(color(_middleBorder));
}
var emoji = _getEmoji(level);
for (var line in message.split('\n')) {
buffer.add(color('$verticalLineAtLevel$emoji$line'));
}
if (includeBox[level]!) buffer.add(color(_bottomBorder));
return buffer;
}
}