-
-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Logger.ts
345 lines (291 loc) · 10.5 KB
/
Logger.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
const moment = require('moment');
const { sprintf } = require('sprintf-js');
const Mutex = require('async-mutex').Mutex;
const writeToFileMutex_ = new Mutex();
export enum TargetType {
Database = 'database',
File = 'file',
Console = 'console',
}
export enum LogLevel {
None = 0,
Error = 10,
Warn = 20,
Info = 30,
Debug = 40,
}
type FormatFunction = (level: LogLevel, targetPrefix?: string)=> string;
interface TargetOptions {
level?: LogLevel;
database?: any;
console?: any;
prefix?: string;
path?: string;
source?: string;
// Default message format
format?: string | FormatFunction;
}
interface Target extends TargetOptions {
type: TargetType;
}
export interface LoggerWrapper {
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
debug: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
info: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
warn: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
error: Function;
}
interface FsDriver {
appendFile: (path: string, content: string, encoding: string)=> Promise<void>;
}
const dummyFsDriver: FsDriver = {
appendFile: async (_path: string, _content: string, _encoding: string) => {},
};
class Logger {
// For backward compatibility
public static LEVEL_NONE = LogLevel.None;
public static LEVEL_ERROR = LogLevel.Error;
public static LEVEL_WARN = LogLevel.Warn;
public static LEVEL_INFO = LogLevel.Info;
public static LEVEL_DEBUG = LogLevel.Debug;
public static fsDriver_: FsDriver|null = null;
private static globalLogger_: Logger|null = null;
private targets_: Target[] = [];
private level_: LogLevel = LogLevel.Info;
private lastDbCleanup_: number = Date.now();
private enabled_ = true;
public static fsDriver() {
if (!Logger.fsDriver_) Logger.fsDriver_ = dummyFsDriver;
return Logger.fsDriver_;
}
public get enabled(): boolean {
return this.enabled_;
}
public set enabled(v: boolean) {
this.enabled_ = v;
}
public status(): string {
const output: string[] = [];
output.push(`Enabled: ${this.enabled}`);
output.push(`Level: ${this.level()}`);
output.push(`Targets: ${this.targets().map(t => t.type).join(', ')}`);
return output.join('\n');
}
public static initializeGlobalLogger(logger: Logger) {
this.globalLogger_ = logger;
}
public static get globalLogger(): Logger {
if (!this.globalLogger_) {
// The global logger normally is initialized early, so we shouldn't
// end up here. However due to early event handlers, it might happen
// and in this case we want to know about it. So we print this
// warning, and also flag the log statements using `[UNINITIALIZED
// GLOBAL LOGGER]` so that we know from where the incorrect log
// statement comes from.
console.warn('Logger: Trying to access globalLogger, but it has not been initialized. Make sure that initializeGlobalLogger() has been called before logging. Will use the console as fallback.');
const output: any = {
log: (level: LogLevel, prefix: string, ...object: any[]) => {
// eslint-disable-next-line no-console
console.info(`[UNINITIALIZED GLOBAL LOGGER] ${this.levelIdToString(level)}: ${prefix}:`, object);
},
};
return output;
// throw new Error('Global logger has not been initialized!!');
}
return this.globalLogger_;
}
public static create(prefix: string): LoggerWrapper {
return {
debug: (...object: any[]) => this.globalLogger.log(LogLevel.Debug, prefix, ...object),
info: (...object: any[]) => this.globalLogger.log(LogLevel.Info, prefix, ...object),
warn: (...object: any[]) => this.globalLogger.log(LogLevel.Warn, prefix, ...object),
error: (...object: any[]) => this.globalLogger.log(LogLevel.Error, prefix, ...object),
};
}
public setLevel(level: LogLevel) {
const previous = this.level_;
this.level_ = level;
return previous;
}
public level() {
return this.level_;
}
public targets() {
return this.targets_;
}
public addTarget(type: TargetType, options: TargetOptions|null = null) {
const target = { type: type };
for (const n in options) {
if (!options.hasOwnProperty(n)) continue;
(target as any)[n] = (options as any)[n];
}
this.targets_.push(target);
}
public objectToString(object: any) {
let output = '';
if (typeof object === 'object') {
if (object instanceof Error) {
object = object as any;
output = object.toString();
if (object.code) output += `\nCode: ${object.code}`;
if (object.headers) output += `\nHeader: ${JSON.stringify(object.headers)}`;
if (object.request) output += `\nRequest: ${object.request.substr ? object.request.substr(0, 1024) : ''}`;
if (object.stack) output += `\n${object.stack}`;
} else {
output = JSON.stringify(object);
}
} else {
output = object;
}
return output;
}
public objectsToString(...object: any[]) {
const output = [];
for (let i = 0; i < object.length; i++) {
output.push(`"${this.objectToString(object[i])}"`);
}
return output.join(', ');
}
public static databaseCreateTableSql() {
const output = `
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY,
source TEXT,
level INT NOT NULL,
message TEXT NOT NULL,
\`timestamp\` INT NOT NULL
);
`;
return output.split('\n').join(' ');
}
// Only for database at the moment
public async lastEntries(limit = 100, options: any = null) {
if (options === null) options = {};
if (!options.levels) options.levels = [LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error];
if (!options.levels.length) return [];
for (let i = 0; i < this.targets_.length; i++) {
const target = this.targets_[i];
if (target.type === 'database') {
let sql = `SELECT * FROM logs WHERE level IN (${options.levels.join(',')}) ORDER BY timestamp DESC`;
if (limit !== null) sql += ` LIMIT ${limit}`;
return await target.database.selectAll(sql);
}
}
return [];
}
public targetLevel(target: Target): LogLevel {
if ('level' in target) return target.level as LogLevel;
return this.level();
}
public log(level: LogLevel, prefix: string | null, ...object: any[]) {
if (!this.targets_.length || !this.enabled) return;
for (let i = 0; i < this.targets_.length; i++) {
const target = this.targets_[i];
const targetPrefix = prefix ? prefix : target.prefix;
if (this.targetLevel(target) < level) continue;
if (target.type === 'console') {
let fn = 'log';
if (level === LogLevel.Error) fn = 'error';
if (level === LogLevel.Warn) fn = 'warn';
if (level === LogLevel.Info) fn = 'info';
const consoleObj = target.console ? target.console : console;
let items: any[] = [];
if (target.format) {
const format = typeof target.format === 'string' ? target.format : target.format(level, targetPrefix);
const s = sprintf(format, {
date_time: moment().format('YYYY-MM-DD HH:mm:ss'),
level: Logger.levelIdToString(level),
prefix: targetPrefix || '',
message: '',
});
items = [s.trim()].concat(...object);
} else {
const prefixItems = [moment().format('HH:mm:ss')];
if (targetPrefix) prefixItems.push(targetPrefix);
items = [`${prefixItems.join(': ')}:`].concat(...object);
}
consoleObj[fn](...items);
} else if (target.type === 'file') {
const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
const line = [timestamp];
if (targetPrefix) line.push(targetPrefix);
line.push(this.objectsToString(...object));
// Write to file using a mutex so that log entries appear in the
// correct order (otherwise, since the async call is not awaited
// by caller, multiple log call in a row are not guaranteed to
// appear in the right order). We also can't use a sync call
// because that would slow down the main process, especially
// when many log operations are being done (eg. during sync in
// dev mode).
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
let release: Function|null = null;
/* eslint-disable-next-line promise/prefer-await-to-then, @typescript-eslint/ban-types -- Old code before rule was applied, Old code before rule was applied */
writeToFileMutex_.acquire().then((r: Function) => {
release = r;
return Logger.fsDriver().appendFile(target.path as string, `${line.join(': ')}\n`, 'utf8');
// eslint-disable-next-line promise/prefer-await-to-then -- Old code before rule was applied
}).catch((error: any) => {
console.error('Cannot write to log file:', error);
// eslint-disable-next-line promise/prefer-await-to-then -- Old code before rule was applied
}).finally(() => {
if (release) release();
});
} else if (target.type === 'database') {
const msg = [];
if (targetPrefix) msg.push(targetPrefix);
msg.push(this.objectsToString(...object));
const queries = [
{
sql: 'INSERT INTO logs (`source`, `level`, `message`, `timestamp`) VALUES (?, ?, ?, ?)',
params: [target.source, level, msg.join(': '), Date.now()],
},
];
const now = Date.now();
if (now - this.lastDbCleanup_ > 1000 * 60 * 60) {
this.lastDbCleanup_ = now;
const dayKeep = 14;
queries.push({
sql: 'DELETE FROM logs WHERE `timestamp` < ?',
params: [now - 1000 * 60 * 60 * 24 * dayKeep],
});
}
target.database.transactionExecBatch(queries);
}
}
}
public error(...object: any[]) {
return this.log(LogLevel.Error, null, ...object);
}
public warn(...object: any[]) {
return this.log(LogLevel.Warn, null, ...object);
}
public info(...object: any[]) {
return this.log(LogLevel.Info, null, ...object);
}
public debug(...object: any[]) {
return this.log(LogLevel.Debug, null, ...object);
}
public static levelStringToId(s: string) {
if (s === 'none') return LogLevel.None;
if (s === 'error') return LogLevel.Error;
if (s === 'warn') return LogLevel.Warn;
if (s === 'info') return LogLevel.Info;
if (s === 'debug') return LogLevel.Debug;
throw new Error(`Unknown log level: ${s}`);
}
public static levelIdToString(id: LogLevel) {
if (id === LogLevel.None) return 'none';
if (id === LogLevel.Error) return 'error';
if (id === LogLevel.Warn) return 'warn';
if (id === LogLevel.Info) return 'info';
if (id === LogLevel.Debug) return 'debug';
throw new Error(`Unknown level ID: ${id}`);
}
public static levelIds() {
return [LogLevel.None, LogLevel.Error, LogLevel.Warn, LogLevel.Info, LogLevel.Debug];
}
}
export default Logger;