-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_repository.dart
73 lines (59 loc) · 1.87 KB
/
log_repository.dart
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
import 'dart:async';
import 'package:drift/drift.dart';
import 'database/database.dart';
import 'models/models.dart';
class LoggerRepository {
LoggerRepository._();
static final LoggerRepository instance = LoggerRepository._();
final database = LogDataBase();
StreamController<Log>? _controller;
Stream<Log> get _getStream();
Future<void> addLog({
required String name,
required DateTime time,
required int level,
required String message,
StackTrace? stackTrace,
}) async {
final log = await database.into(database.logEntries).insertReturning(
LogEntriesCompanion.insert(
name: name,
level: level,
time: time,
message: message,
stackTrace: Value(stackTrace?.toString()),
),
);
_publishAddLog(Log.fromDBEntrty(log));
}
Future<List<Log>> getLogs() async {
return (await (database.select(database.logEntries)
..orderBy([(t) => OrderingTerm.desc(t.id)]))
.get())
.map((e) => Log.fromDBEntrty(e))
.toList();
}
Future<Log?> getLog(int logId) async {
return (await ((database.select(database.logEntries)
..where((item) => item.id.isValue(logId))))
.get())
.map((e) => Log.fromDBEntrty(e))
.firstOrNull;
}
Future<int> cleanOldLogs(
{Duration keepLogs = const Duration(days: 7)}) async {
final now = DateTime.now();
final compateDate = now.subtract(keepLogs);
return (database.delete(database.logEntries)
..where((item) => item.time.isSmallerThanValue(compateDate)))
.go();
}
void clearListeners() {
_controller?.close();
_controller = null;
}
Stream<Log> _getStream() {
return (_controller ??= StreamController<Log>.broadcast(sync: true)).stream;
}
void _publishAddLog(Log log) => _controller?.add(log);
}