-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcustom_file_output.dart
More file actions
53 lines (44 loc) · 1.27 KB
/
custom_file_output.dart
File metadata and controls
53 lines (44 loc) · 1.27 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
import 'dart:convert';
import 'dart:io';
import 'package:logger/logger.dart';
/// Custom implementation of [LogOutput] to write the log output into a file.
final class CustomFileOutput extends LogOutput {
final File _file;
final bool _overrideExisting;
final Encoding _encoding;
/// Regex used to remove ansi color codes from log files.
final _ansiPattern = RegExp(r'\x1B\[\d+(;\d+)*m');
/// It's a reference to [_file] used to write logs inside.
IOSink? _sink;
CustomFileOutput({
required File file,
bool overrideExisting = false,
Encoding encoding = utf8,
}) : _encoding = encoding,
_overrideExisting = overrideExisting,
_file = file;
@override
Future<void> init() async {
_sink = _file.openWrite(
mode: _overrideExisting ? FileMode.writeOnly : FileMode.writeOnlyAppend,
encoding: _encoding,
);
}
@override
void output(OutputEvent event) async {
// File may have been deleted.
if (!_file.existsSync()) {
await _file.create();
await destroy();
await init();
}
_sink?.writeAll(
event.lines.map((line) => line.replaceAll(_ansiPattern, '')), '\n');
_sink?.writeln();
}
@override
Future<void> destroy() async {
await _sink?.flush();
await _sink?.close();
}
}