-
Notifications
You must be signed in to change notification settings - Fork 2
/
common.ts
123 lines (103 loc) · 3.07 KB
/
common.ts
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
const FS = require('fs');
export class Options {
static debugTokens = false;
static debugExpression = true;
static debugExecution = false;
static debugTree = false;
static delegate;
}
export function debug(type, title, obj = null) {
logger.log(title);
if (type == 'execution' && !Options.debugExecution)
return;
if (type == 'tokens' && !Options.debugTokens)
return;
if (type == 'tree' && !Options.debugTree)
return;
console.log(title);
if (obj) {
console.log(obj);
logger.log(JSON.stringify(obj));
}
}
export class Logger {
debugMsgs = [];
toConsole = true;
toFile = null;
callback = null;
constructor({ toConsole = true, toFile = '', callback = null }) {
this.setOptions({ toConsole, toFile, callback });
}
setOptions({ toConsole, toFile, callback }) {
this.toConsole = toConsole;
this.toFile = toFile;
this.callback = callback;
}
msg(message, type = 'log') {
if (this.toConsole)
console.log(message);
if (this.callback) {
this.callback(message, type);
}
this.debugMsgs.push({ message, type });
}
clear() {
this.debugMsgs = [];
}
get() {
return this.debugMsgs;
}
debug(message) {
this.msg(message, 'debug');
}
warn(message) {
this.msg(message, 'warn');
}
log(message) {
this.msg(message);
}
error(err) {
if (typeof err === 'object') {
if (err.message) {
this.msg(err.message, 'error');
console.log('\nError Message: ' + err.message)
}
if (err.stack) {
console.log('\nStacktrace:')
console.log('====================')
console.log(err.stack);
this.log(err.stack);
}
} else {
this.msg(err, 'error');
}
throw new Error(err);
}
async save(filename) {
console.log("writing to:" + filename + " " + this.debugMsgs.length);
let id = FS.openSync(filename, 'w', 666);
{
FS.writeSync(id, 'Started at: ' + new Date().toISOString() + "\n", null, 'utf8');
let l = 0;
for (l = 0; l < this.debugMsgs.length; l++) {
let msg = this.debugMsgs[l];
if (msg.type == 'error') {
let line = msg.type + ": at line " + (l + 1) + " " + msg.message;
FS.writeSync(id, line + "\n", null, 'utf8');
}
}
for (l = 0; l < this.debugMsgs.length; l++) {
let msg = this.debugMsgs[l];
let line;
if (msg.type == 'eror')
line = msg.type + ":" + msg.message;
else
line = msg.message;
FS.writeSync(id, line + "\n", null, 'utf8');
}
FS.closeSync(id);
this.clear();
}
}
}
export const logger = new Logger({ toConsole: false });