1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const path = require("path");
|
4 | const timestamp = () => new Date().toISOString();
|
5 | let timer;
|
6 | const wait = (ms) => new Promise(resolve => {
|
7 | if (timer)
|
8 | timer.unref();
|
9 | timer = setTimeout(() => resolve(), ms);
|
10 | });
|
11 | function chomp(s) {
|
12 | if (s.endsWith('\n'))
|
13 | return s.replace(/\n$/, '');
|
14 | return s;
|
15 | }
|
16 | class Logger {
|
17 |
|
18 | constructor(file) {
|
19 | this.file = file;
|
20 | this.flushing = Promise.resolve();
|
21 | this.buffer = [];
|
22 | }
|
23 | log(msg) {
|
24 | const stripAnsi = require('strip-ansi');
|
25 | msg = stripAnsi(chomp(msg));
|
26 | const lines = msg.split('\n').map(l => `${timestamp()} ${l}`.trimRight());
|
27 | this.buffer.push(...lines);
|
28 |
|
29 | this.flush(50).catch(console.error);
|
30 | }
|
31 | async flush(waitForMs = 0) {
|
32 | await wait(waitForMs);
|
33 | this.flushing = this.flushing.then(async () => {
|
34 | if (this.buffer.length === 0)
|
35 | return;
|
36 | const mylines = this.buffer;
|
37 | this.buffer = [];
|
38 | const fs = require('fs-extra');
|
39 | await fs.mkdirp(path.dirname(this.file));
|
40 | await fs.appendFile(this.file, mylines.join('\n') + '\n');
|
41 | });
|
42 | await this.flushing;
|
43 | }
|
44 | }
|
45 | exports.Logger = Logger;
|