@denodnt/logger
Version:
deno logger available for deno and NPM
128 lines (127 loc) • 3.86 kB
JavaScript
var _a, _b, _c;
import * as dntShim from "./_dnt.shims.js";
import Writable from "./writable.js";
import { exists } from "./fs.js";
import Types from "./types.js";
/**
* Writer class
*/
class Writer {
/**
* Writer constructor
* @param param0
* @returns
*/
constructor({ maxBytes, maxBackupCount }) {
Object.defineProperty(this, "maxBytes", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "maxBackupCount", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "pathWriterMap", {
enumerable: true,
configurable: true,
writable: true,
value: new Map()
});
Object.defineProperty(this, _a, {
enumerable: true,
configurable: true,
writable: true,
value: ""
});
Object.defineProperty(this, _b, {
enumerable: true,
configurable: true,
writable: true,
value: ""
});
Object.defineProperty(this, _c, {
enumerable: true,
configurable: true,
writable: true,
value: ""
});
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;
}
async newWriter(path) {
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 }) {
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) {
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 dntShim.Deno.rename(source, dest);
}
}
}
else {
const dest = path + "." + Date.now();
await dntShim.Deno.rename(path, dest);
}
}
}
_a = Types.INFO, _b = Types.WARN, _c = Types.ERROR;
export default Writer;