/
logging.js
70 lines (58 loc) · 1.81 KB
/
logging.js
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
/**
* Created by teklof on 8.11.16.
*/
"use strict";
const $ = require("highland");
const _ = require("lodash");
const bunyan = require("bunyan");
let rootLogger;
const defaults = {
name: "s4qs-rs"
, streams: [
{level: "trace", stream: process.stdout}
]
, serializers: {err: bunyan.stdSerializers.err}
};
function transformBunyanLevel(lvl) {
let newLvl = Math.min(bunyan.ERROR, Math.max(bunyan.DEBUG, lvl));
return (bunyan.nameFromLevel[newLvl] || "unknown").toUpperCase();
}
function WantedOutput(bunyanOutput) {
this.ts = bunyanOutput.time;
this.bunyanLevel = bunyanOutput.level;
this.level = transformBunyanLevel(bunyanOutput.level);
_.defaults(this, _.omit(bunyanOutput, "time", "level", "v", "hostname", "name", "service"))
}
function confStream(opts) {
return streamOptions[opts.stream](opts)
}
const streamOptions = {
"stdout": (opt) => {opt.stream = process.stdout; return opt}
, "stderr": (opt) => { opt.stream = process.stderr; return opt}
, "massaged": (opt) => {
const stream = $();
stream.map(logObj => new WantedOutput(logObj)).map(row => JSON.stringify(row)+"\n").pipe(process.stderr);
opt.stream = stream;
opt.type = "raw";
return opt;
}
};
function isInited() {
return !!rootLogger;
}
exports.initLogging = function(options) {
const clonedOpts = _.cloneDeep(options) || {};
if(_.isArray(clonedOpts.streams)) {
clonedOpts.streams = clonedOpts.streams.map(confStream);
}
const optsWithDefaults = _.defaults(clonedOpts, defaults);
rootLogger = bunyan.createLogger(optsWithDefaults);
rootLogger.info({module: "logging"}, "root logger initialized");
return exports;
};
exports.getLogger = function(fields) {
if(!isInited()) {
throw new Error("Logging hasn't been initialized: call initLogging first");
}
return rootLogger.child(fields || {});
};