co-log
Version:
Port of log4js work for node.RequestId is supported.
96 lines • 3.26 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Log = void 0;
const co_util_1 = __importDefault(require("co-util"));
const log4js_1 = __importDefault(require("log4js"));
const { AsyncLocalStorage } = require('async_hooks');
class Log {
constructor(opts) {
opts = opts || {};
opts.path = opts.path || 'log';
this.opts = opts;
this.asyncLocalStorage = new AsyncLocalStorage();
if (!opts.path.endsWith('/'))
opts.path += '/';
log4js_1.default.configure({
appenders: {
console: {
type: 'console',
layout: {
type: 'pattern',
"pattern": "%[[%d{yyyy-MM-dd hh:mm:ss.SSS}] [%p] -%] %m",
}
},
default: {
type: 'dateFile',
filename: opts.path, pattern: "yyyy-MM-dd.log",
alwaysIncludePattern: true,
layout: {
type: 'pattern',
"pattern": "[%d{yyyy-MM-dd hh:mm:ss.SSS}] [%p] - %m",
}
}
},
categories: {
console: { appenders: ['console', 'default'], level: 'trace' },
default: { appenders: ['default'], level: 'trace' },
}
});
const log = log4js_1.default.getLogger('console');
console.log = (...args) => {
let requestId = this.getRequestId();
if (requestId)
args.unshift(requestId);
if (this.isError(args)) {
log.error(...args);
}
else {
log.info(...args);
}
};
let arr = ['info', 'warn', 'debug', 'error', 'fatal', 'trace'];
for (let key of arr) {
console[key] = (...args) => {
let requestId = this.getRequestId();
if (requestId)
args.unshift(requestId);
log[key](...args);
};
}
}
getRequestId() {
let requestId = this.asyncLocalStorage.getStore();
return requestId;
}
setRequestId(requestId) {
this.asyncLocalStorage.enterWith(requestId || co_util_1.default.uuid());
}
setRequestIdForKoa() {
return async (ctx, next) => {
ctx.requestId = ctx.requestId || co_util_1.default.uuid();
await this.asyncLocalStorage.run(ctx.requestId, () => {
return next();
});
};
}
setRequestIdForExpress() {
return async (req, res, next) => {
req.requestId = req.requestId || co_util_1.default.uuid();
await this.asyncLocalStorage.run(req.requestId, () => {
return next();
});
};
}
isError(args) {
for (let arg of args) {
if (arg instanceof Error)
return true;
}
return false;
}
}
exports.Log = Log;
//# sourceMappingURL=log.js.map