perfect-logger
Version:
A zero-dependency, isomorphic logger for Node.js and Browsers with plugin support.
62 lines (61 loc) • 1.96 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseAppender = void 0;
const constants_1 = require("../constants");
class BaseAppender {
constructor(name, config, defaultConfig = {}) {
var _a, _b, _c;
this.buffer = [];
this.timer = null;
this.name = name;
const finalConfig = { ...defaultConfig, ...config };
this.minLevel = (_a = finalConfig.minLevel) !== null && _a !== void 0 ? _a : constants_1.LogLevel.INFO;
this.batchSize = (_b = finalConfig.batchSize) !== null && _b !== void 0 ? _b : 1;
this.batchInterval = (_c = finalConfig.batchInterval) !== null && _c !== void 0 ? _c : 1000;
this.timezone = finalConfig.timezone;
if (this.batchSize > 1) {
this.startTimer();
}
}
async log(entry) {
if (entry.level >= this.minLevel) {
if (this.batchSize > 1) {
this.buffer.push(entry);
if (this.buffer.length >= this.batchSize) {
await this.flush();
}
}
else {
await this.handle(entry);
}
}
}
async flush() {
this.stopTimer();
if (this.buffer.length > 0) {
const batch = this.buffer.slice();
this.buffer = [];
if (this.handleBatch) {
await this.handleBatch(batch);
}
else {
for (const entry of batch) {
await this.handle(entry);
}
}
}
this.startTimer();
}
startTimer() {
if (this.batchSize > 1 && !this.timer) {
this.timer = setInterval(() => this.flush(), this.batchInterval);
}
}
stopTimer() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
}
exports.BaseAppender = BaseAppender;