-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
writer.ts
102 lines (92 loc) · 2.68 KB
/
writer.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
import Writable from "./writable.ts";
import { exists } from "./deps.ts";
import type { WriterConstructor, WriterWrite } from "./interface.ts";
import Types from "./types.ts";
/**
* Writer class
*/
export default class Writer {
private maxBytes?: number;
private maxBackupCount?: number;
private pathWriterMap = new Map();
private [Types.DEBUG]: string = "";
private [Types.INFO]: string = "";
private [Types.LOG]: string = "";
private [Types.WARN]: string = "";
private [Types.ERROR]: string = "";
/**
* Writer constructor
* @param param0
* @returns
*/
constructor({ maxBytes, maxBackupCount }: WriterConstructor) {
if (maxBytes !== undefined && maxBytes <= 0) {
throw new Error("maxBytes cannot be less than 1");
}
this.maxBytes = maxBytes;
if (maxBackupCount === undefined) return;
if (!maxBytes) {
throw new Error("maxBackupCount must work with maxBytes");
}
if (maxBackupCount <= 0) {
throw new Error("maxBackupCount cannot be less than 1");
}
this.maxBackupCount = maxBackupCount;
}
private async newWriter(path: string) {
const writer = new Writable(path);
await writer.setup();
this.pathWriterMap.set(path, writer);
return writer;
}
/**
* Write message to file
* @param param0
* @returns
*/
async write({ path, msg, type }: WriterWrite): Promise<void> {
const msgByteLength = msg.byteLength;
if (this.pathWriterMap.has(path)) {
const writer = this.pathWriterMap.get(path);
const currentSize = writer.currentSize;
const size = currentSize + msgByteLength;
if (this.maxBytes && size > this.maxBytes) {
writer.close();
this.rotateLogFiles(path);
const _writer = await this.newWriter(path);
await _writer.write(msg);
} else {
await writer.write(msg);
}
return;
}
const typePath = this[type];
if (typePath) {
const pathWriter = this.pathWriterMap.get(typePath);
if (pathWriter && pathWriter.close) pathWriter.close();
this.pathWriterMap.delete(typePath);
}
this[type] = path;
const writer = await this.newWriter(path);
await writer.write(msg);
}
/**
* Rotate log files
* @param path
*/
async rotateLogFiles(path: string): Promise<void> {
if (this.maxBackupCount) {
for (let i = this.maxBackupCount - 1; i >= 0; i--) {
const source = path + (i === 0 ? "" : "." + i);
const dest = path + "." + (i + 1);
const exist = await exists(source);
if (exist) {
await Deno.rename(source, dest);
}
}
} else {
const dest = path + "." + Date.now();
await Deno.rename(path, dest);
}
}
}