log-vault
Version:
A generator of Winston logger instance with pre-defined configurable transports and formats and extra functionality.
189 lines (188 loc) • 8.99 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LogVault = void 0;
const winston_1 = __importStar(require("winston"));
const _1 = require(".");
const util_1 = require("./util");
const transports_1 = require("winston/lib/winston/transports");
const defaults_1 = require("./defaults");
const formats_1 = require("./formats");
require("winston-daily-rotate-file");
const path_1 = require("path");
const formatMongo_1 = require("./formats/formatMongo");
require("winston-mongodb");
const winston_loki_1 = __importDefault(require("winston-loki"));
const transports_2 = require("./transports");
class LogVault {
constructor(opts = {}) {
const { projectName = (0, util_1.projectDirName)(), truncateOptions = defaults_1.defaultTruncateOptions, maskOptions = defaults_1.defaultMaskFieldsOptions, ...winstonOpts } = opts;
this.projectName = projectName;
this.truncateOptions = truncateOptions;
this.maskOptions = maskOptions;
this.logger = (0, winston_1.createLogger)({
levels: defaults_1.defaultLevels,
level: "http",
format: winston_1.format.errors({ stack: true }),
exitOnError: false,
defaultMeta: {
[_1.META]: this.defaultMeta
},
...winstonOpts
});
}
withConsole(opts = {}) {
const { colors = defaults_1.defaultColors, inspectOptions = defaults_1.defaultInspectOptions, ...winstonConsoleOpts } = opts;
winston_1.default.addColors(colors);
this.logger.add(new transports_1.Console({
format: winston_1.format.combine(winston_1.format.timestamp({ format: defaults_1.defaultTimestamp }), winston_1.format.colorize(), (0, formats_1.formatError)(), (0, formats_1.formatArrangeOutput)({ truncateOptions: this.truncateOptions }), (0, formats_1.formatMaskFields)({ ...this.maskOptions }), (0, formats_1.formatConsole)({ inspectOptions })),
handleExceptions: true,
handleRejections: true,
...winstonConsoleOpts
}));
return this;
}
withFiles(opts = {}) {
const { errorLevel = "error", ...dailyRotateFileOptions } = opts;
if (!Object.keys(this.logger.levels).includes(errorLevel))
throw new Error("Files errorLevel should be listed in logger levels");
const filesFormat = winston_1.format.combine(winston_1.format.timestamp({ format: defaults_1.defaultTimestamp }), (0, formats_1.formatCustomOptions)(), (0, formats_1.formatError)(), (0, formats_1.formatArrangeOutput)({ truncateOptions: this.truncateOptions }), (0, formats_1.formatMaskFields)({ ...this.maskOptions }), (0, formats_1.formatMeta)(), winston_1.format.json({ space: 2 }));
const commonDailyRotateOpts = {
dirname: (0, path_1.resolve)("./", "logs"),
maxSize: "1m",
maxFiles: "30d",
datePattern: "YYYY-MM-DD",
format: filesFormat,
...dailyRotateFileOptions,
stream: undefined
};
this.logger.add(new transports_1.DailyRotateFile({
filename: `${this.logger.level}-%DATE%.log`,
...commonDailyRotateOpts,
handleExceptions: false,
handleRejections: false
}));
this.logger.add(new transports_1.DailyRotateFile({
filename: `${errorLevel}-%DATE%.log`,
...commonDailyRotateOpts,
level: errorLevel,
handleExceptions: true,
handleRejections: true
}));
return this;
}
withMongo(opts) {
const { handleExceptions = true, handleRejections = false, ...mongoDBConnectionOptions } = opts;
const mongoTransport = new winston_1.default.transports.MongoDB({
level: this.logger.level,
metaKey: "meta",
format: winston_1.format.combine(winston_1.format.timestamp({ format: defaults_1.defaultTimestamp }), (0, formats_1.formatCustomOptions)(), (0, formats_1.formatError)(), (0, formats_1.formatArrangeOutput)({ truncateOptions: this.truncateOptions }), (0, formats_1.formatMaskFields)({ ...this.maskOptions }), (0, formats_1.formatMeta)(), (0, formatMongo_1.formatMongo)()),
...mongoDBConnectionOptions
});
this.logger.add(mongoTransport);
if (handleExceptions)
this.logger.exceptions.handle(mongoTransport);
if (handleRejections)
this.logger.rejections.handle(mongoTransport);
return this;
}
withLoki(opts = {}) {
this.logger.add(new winston_loki_1.default({
host: "http://localhost:3100",
json: true,
format: winston_1.format.combine(winston_1.format.timestamp({ format: defaults_1.defaultTimestamp }), (0, formats_1.formatCustomOptions)(), (0, formats_1.formatError)(), (0, formats_1.formatArrangeOutput)({ truncateOptions: this.truncateOptions }), (0, formats_1.formatMaskFields)({ ...this.maskOptions }), (0, formats_1.formatMeta)(), (0, formats_1.formatLoki)()),
useWinstonMetaAsLabels: true,
...opts
}));
return this;
}
withNotificator(notificator) {
notificator.on("failed", (job, err) => {
this.logger.error("Notification delivery failed", {
err: err.message,
payload: job === null || job === void 0 ? void 0 : job.data,
[_1.SKIP_NOTIFICATIONS]: true
});
});
return this;
}
withNotifications(opts = {}) {
this.logger.add(new transports_2.NotificationsTransport({
name: this.projectName,
...opts,
format: winston_1.format.combine((0, winston_1.format)((info) => (info[_1.SKIP_NOTIFICATIONS] ? false : info))(), winston_1.format.timestamp({ format: defaults_1.defaultTimestamp }), (0, formats_1.formatCustomOptions)(), (0, formats_1.formatError)(), (0, formats_1.formatArrangeOutput)({ truncateOptions: this.truncateOptions }), (0, formats_1.formatMaskFields)({ ...this.maskOptions }), (0, formats_1.formatMeta)(), (0, formats_1.formatNotifications)())
}));
return this;
}
captureConsole(opts = {
matchLevels: { log: "info", warn: "warn", info: "info", error: "error" }
}) {
const levels = Object.keys(this.logger.levels);
Object.keys(opts.matchLevels).forEach((key) => {
if (!levels.includes(opts.matchLevels[key]))
throw new Error(`${key} is not presented in logger levels`);
});
console.log = (...args) => {
return this.logger[opts.matchLevels.log](...args);
};
console.warn = (...args) => {
return this.logger[opts.matchLevels.warn](...args);
};
console.info = (...args) => {
return this.logger[opts.matchLevels.info](...args);
};
console.error = (...args) => {
return this.logger[opts.matchLevels.error](...args);
};
return this;
}
uncaptureConsole() {
console.log = Object.getPrototypeOf(console).log;
console.warn = Object.getPrototypeOf(console).warn;
console.info = Object.getPrototypeOf(console).info;
return this;
}
get defaultMeta() {
return {
project: this.projectName,
process: process.env.npm_package_name,
environment: process.env.NODE_ENV
};
}
}
exports.LogVault = LogVault;