Repository navigation
Expand file tree
/
Copy pathFrusterLogger.js
More file actions
175 lines (148 loc) · 5.24 KB
/
Copy pathFrusterLogger.js
File metadata and controls
175 lines (148 loc) · 5.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
const winston = require("winston");
const uuid = require("uuid");
const moment = require("moment-timezone");
const constants = require("./constants");
const LOG_LEVEL_REMOTE_NAME = "remote";
const LOG_LEVEL_AUDIT_NAME = "audit";
let bus;
class FrusterLogger extends winston.Logger {
constructor(logLevel = "info", timestampTimezone = "Europe/Stockholm", remoteLogLevel = "error") {
super({
exitOnError: false,
level: logLevel,
levels: constants.levels,
colors: constants.levelColors
});
this.logLevel = logLevel;
this.timestampTimezone = timestampTimezone;
this.remoteLogLevel = remoteLogLevel;
this._configureConsoleLogging();
this._attachRemoteLogs();
}
/**
* Attach and intercepts log levels that will be posted on bus, i.e.
* to fruster-log-service.
*
* Note that log.audit() and log.remote() will always post to remote
* no matter of config.
*/
_attachRemoteLogs() {
const tresholdLevel = constants.levels[this.remoteLogLevel];
let levelsToAttach = [];
if (tresholdLevel !== undefined /* it can be 0, hence undefined check */) {
// get all log levels from and "above" remote log level
levelsToAttach = Object.keys(constants.levels)
.filter(levelName => constants.levels[levelName] <= tresholdLevel);
}
// remote and audit log always log to remote no matter of config
if (!levelsToAttach.includes(LOG_LEVEL_REMOTE_NAME)) {
levelsToAttach.push(LOG_LEVEL_REMOTE_NAME);
}
if (!levelsToAttach.includes(LOG_LEVEL_AUDIT_NAME)) {
levelsToAttach.push(LOG_LEVEL_AUDIT_NAME);
}
levelsToAttach.forEach((level) => {
const superLog = this[level];
if (level === LOG_LEVEL_AUDIT_NAME) {
this[level] = (userId, msg, payload) => {
superLog(`[${userId}] ${msg}`);
this._publishOnBus(FrusterLogger.AUDIT_LOG_SUBJECT, {
userId, msg, payload, level
});
};
} else {
this[level] = (...msg) => {
superLog(...msg);
this._publishOnBus(FrusterLogger.REMOTE_LOG_SUBJECT, {
level, msg
});
};
}
});
}
_publishOnBus(subject, data) {
if (!bus) {
// Lazy require fruster-bus to avoid hassle with circular dependencies
try {
bus = require("fruster-bus");
} catch (err) { }
}
// fruster-bus should expose better flag or function to check if connect
// but this will do for now
const isConnected = bus && !!bus.request;
if (isConnected) {
try {
bus.publish(subject, {
reqId: uuid.v4(),
data
});
} catch (err) {
// Nothing to do, bus is not connected.
}
}
}
/**
* Enable logging to Papertrail using remote syslog.
*
* @param {String} syslogHostAndPort
* @param {String} syslogName
* @param {String} syslogProgram
*/
enablePapertrailLogging(syslogHostAndPort, syslogName, syslogProgram) {
require("winston-papertrail").Papertrail;
const syslogHostAndPortSplit = syslogHostAndPort.split(":");
let winstonPapertrail = new winston.transports.Papertrail({
host: syslogHostAndPortSplit[0],
port: syslogHostAndPortSplit[1],
hostname: syslogName,
program: syslogProgram,
level: this.logLevel
});
winstonPapertrail.on("error", function (err) {
console.error(`Failed connecting to papertrail ${syslogHostAndPort}`, err);
});
super.add(winstonPapertrail, null, true);
}
_configureConsoleLogging() {
const consoleTransport = new winston.transports.Console({
humanReadableUnhandledException: true,
handleExceptions: true,
json: false,
colorize: "all",
prettyPrint: true,
timestamp: () => this._getTimestamp()
});
super.add(consoleTransport, null, true);
}
/**
* Function that returns timestamp used for console log.
* Note that timestamp is not used for remote syslog.
*/
_getTimestamp() {
const timeZonedDate = moment(new Date()).tz(this.timestampTimezone);
return `[${timeZonedDate.format("YYYY-MM-DD hh:mm:ss")}]`;
}
/**
* Audit log.
*
* @param {String} userId
* @param {String} msg
* @param {any=} payload
*/
audit(userId, msg, payload) {
// Will be overridden in `_attachRemoteLogs()` but kept
// here to make intellisense work.
}
/**
* Remote log.
*
* @param {Array=} args
*/
remote(...args) {
// Will be overridden in `_attachRemoteLogs()` but kept
// here to make intellisense work.
}
}
FrusterLogger.AUDIT_LOG_SUBJECT = "log";
FrusterLogger.REMOTE_LOG_SUBJECT = "log";
module.exports = FrusterLogger;