Line data Source code
1 : import 'dart:async';
2 : import 'dart:convert';
3 : import 'dart:io';
4 :
5 : import 'package:drift/drift.dart';
6 : import 'package:path/path.dart';
7 : import 'package:path_provider/path_provider.dart';
8 : import 'package:the_logger/src/db/logger_database.dart';
9 :
10 : /// Write all logs to a gzipped JSON file, return the file path.
11 1 : Future<String> writeLogsToFile(
12 : LoggerDatabase database,
13 : String filename,
14 : ) async {
15 1 : final filePath = join(
16 2 : (await getTemporaryDirectory()).path,
17 1 : '$filename.gzip',
18 : );
19 :
20 1 : final file = File(filePath);
21 2 : await file.parent.create(recursive: true);
22 :
23 : try {
24 1 : await file.delete();
25 1 : } on FileSystemException catch (_) {}
26 :
27 1 : final ioSink = file.openWrite();
28 2 : final sink = gzip.encoder.startChunkedConversion(ioSink)
29 2 : ..add(utf8.encode('{\n "logs": [\n'));
30 :
31 : const batchSize = 1000;
32 : var offset = 0;
33 : var isFirst = true;
34 :
35 : while (true) {
36 : final rows = await database
37 1 : .customSelect(
38 : 'SELECT logger_name, id, record_timestamp, session_id, level, '
39 : 'message, error, stack_trace, time '
40 : 'FROM records ORDER BY record_timestamp ASC '
41 : 'LIMIT ? OFFSET ?',
42 3 : variables: [Variable.withInt(batchSize), Variable.withInt(offset)],
43 : )
44 1 : .get();
45 :
46 1 : if (rows.isEmpty) break;
47 :
48 2 : for (final row in rows) {
49 : final comma = isFirst ? '' : ',\n';
50 5 : sink.add(utf8.encode('$comma ${json.encode(row.data)}'));
51 : isFirst = false;
52 : }
53 :
54 1 : offset += batchSize;
55 : }
56 :
57 : sink
58 2 : ..add(utf8.encode('\n ]\n}'))
59 1 : ..close();
60 1 : await ioSink.flush();
61 : // Tests fail when this is awaited (same as original sqflite code).
62 2 : unawaited(ioSink.close());
63 :
64 : return filePath;
65 : }
|