Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/core/models/SessionLogsTable.ts
1028 views
1
import { Database as SqliteDatabase } from 'better-sqlite3';
2
import { ILogEntry } from '@secret-agent/commons/Logger';
3
import SqliteTable from '@secret-agent/commons/SqliteTable';
4
5
export default class SessionLogsTable extends SqliteTable<ISessionLogRecord> {
6
constructor(readonly db: SqliteDatabase) {
7
super(db, 'SessionLogs', [
8
['id', 'INTEGER'],
9
['timestamp', 'INTEGER'],
10
['action', 'TEXT'],
11
['level', 'TEXT'],
12
['module', 'TEXT'],
13
['isGlobal', 'INTEGER'],
14
['parentId', 'INTEGER'],
15
['data', 'TEXT'],
16
]);
17
}
18
19
public insert(log: ILogEntry) {
20
// ignore logging these to the db - they're in the Commands table
21
if (log.action === 'Command.run' || log.action === 'Command.done') return;
22
if (log.data instanceof Error) {
23
log.data = {
24
stack: log.data.stack,
25
...log.data,
26
};
27
}
28
const context = log.data?.context;
29
30
let data = log.data
31
? JSON.stringify(log.data, (key, value) => {
32
if (value instanceof Error) {
33
return {
34
stack: value.stack,
35
toString: value.toString(),
36
...value,
37
};
38
}
39
if (value === context) {
40
if (!Object.keys(value).length) return undefined;
41
42
const ctx: any = {};
43
for (const x of Object.keys(value)) {
44
if (x === 'sessionId' || x === 'browserContextId') continue;
45
ctx[x] = value[x];
46
}
47
if (!Object.keys(ctx).length) return undefined;
48
return ctx;
49
}
50
return value;
51
})
52
: null;
53
if (data === '{}') data = undefined;
54
55
return this.queuePendingInsert([
56
log.id,
57
log.timestamp.getTime(),
58
log.action,
59
log.level,
60
log.module,
61
!log.sessionId ? 1 : undefined,
62
log.parentId,
63
data,
64
]);
65
}
66
67
public allErrors() {
68
return this.db
69
.prepare(`select * from ${this.tableName} where level = 'error'`)
70
.all() as ISessionLogRecord[];
71
}
72
}
73
74
export interface ISessionLogRecord {
75
id: number;
76
timestamp: number;
77
action: string;
78
level: string;
79
module: string;
80
isGlobal?: boolean;
81
parentId?: number;
82
data?: any;
83
}
84
85