-
Notifications
You must be signed in to change notification settings - Fork 569
/
handlers.ts
91 lines (71 loc) · 2.06 KB
/
handlers.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
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { open, File, Writer } from "deno";
import { getLevelByName } from "./levels.ts";
import { LogRecord } from "./logger.ts";
const DEFAULT_FORMATTER = "{levelName} {msg}";
type FormatterFunction = (logRecord: LogRecord) => string;
interface HandlerOptions {
formatter?: string | FormatterFunction;
}
export class BaseHandler {
level: number;
levelName: string;
formatter: string | FormatterFunction;
constructor(levelName: string, options: HandlerOptions = {}) {
this.level = getLevelByName(levelName);
this.levelName = levelName;
this.formatter = options.formatter || DEFAULT_FORMATTER;
}
handle(logRecord: LogRecord) {
if (this.level > logRecord.level) return;
const msg = this.format(logRecord);
return this.log(msg);
}
format(logRecord: LogRecord): string {
if (this.formatter instanceof Function) {
return this.formatter(logRecord);
}
return this.formatter.replace(/{(\S+)}/g, (match, p1) => {
const value = logRecord[p1];
// do not interpolate missing values
if (!value) {
return match;
}
return value;
});
}
log(msg: string) {}
async setup() {}
async destroy() {}
}
export class ConsoleHandler extends BaseHandler {
log(msg: string) {
console.log(msg);
}
}
export abstract class WriterHandler extends BaseHandler {
protected _writer: Writer;
private _encoder = new TextEncoder();
log(msg: string) {
this._writer.write(this._encoder.encode(msg + "\n"));
}
}
interface FileHandlerOptions extends HandlerOptions {
filename: string;
}
export class FileHandler extends WriterHandler {
private _file: File;
private _filename: string;
constructor(levelName: string, options: FileHandlerOptions) {
super(levelName, options);
this._filename = options.filename;
}
async setup() {
// open file in append mode - write only
this._file = await open(this._filename, "a");
this._writer = this._file;
}
async destroy() {
await this._file.close();
}
}