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