@juntoz/azure-function-logger-papertrail
Version:
Quick logger that enables the function to log to the default logger (console) and also to papertrail
104 lines (87 loc) • 3.19 kB
JavaScript
const winston = require('winston');
require('winston-syslog');
var path = require('path');
var appDir = path.dirname(require.main.filename);
// singleton list that is shared across instances and can serve to avoid creating expensive logger every time
var _papertrailList = [];
class Logger {
constructor(papertrailConfig, ctxLog, logLevel) {
logLevel = logLevel || 'info';
this.app_name = papertrailConfig.app ? papertrailConfig.app : appDir;
// The papertrail logger will be static instance because it will be shared across all functions executions
if (papertrailConfig.host) {
if (!_papertrailList[this.app_name]) {
_papertrailList[this.app_name] = winston.createLogger({
level: logLevel,
format: winston.format.json(),
transports: [
new winston.transports.Syslog({
host: papertrailConfig.host,
port: papertrailConfig.port,
app_name: this.app_name
})
]
});
}
}
// The context logger lifetime is only for this function execution
this._loggerThisCtx = winston.createLogger({
level: logLevel,
format: winston.format.json(),
transports: [
new _AzFuncCtxLoggerTransport({
ctxLog: ctxLog
})
]
});
}
end() {
// NOTE: only end the local context logger, singleton papertrail logger must remain
if (this._loggerThisCtx) {
this._loggerThisCtx.end();
}
this._loggerThisCtx = null;
}
verbose(msg) {
this.debug(msg);
}
debug(msg) {
[_papertrailList[this.app_name], this._loggerThisCtx].forEach((l) => l && l.debug(msg));
}
info(msg) {
[_papertrailList[this.app_name], this._loggerThisCtx].forEach((l) => l && l.info(msg));
}
warn(msg) {
[_papertrailList[this.app_name], this._loggerThisCtx].forEach((l) => l && l.warn(msg));
}
error(msg) {
[_papertrailList[this.app_name], this._loggerThisCtx].forEach((l) => l && l.error(msg));
}
}
class _AzFuncCtxLoggerTransport extends require('winston-transport') {
constructor(opts) {
super(opts);
this.ctxLog = opts.ctxLog;
}
log(info, callback) {
switch(info.level) {
case "verbose":
case "debug":
this.ctxLog.verbose(info.message);
break;
case "info":
this.ctxLog.info(info.message);
break;
case "warn":
this.ctxLog.warn(info.message);
break;
case "error":
this.ctxLog.error(info.message);
break;
}
this.emit('logged', info);
// Perform the writing to the remote service
callback();
}
};
module.exports = Logger;