Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
84 lines (67 loc) · 1.89 KB
/
Copy pathapp.js
File metadata and controls
84 lines (67 loc) · 1.89 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
const log = require("fruster-log");
const conf = require("./conf");
const nats = require("nats");
const health = require("fruster-health");
const mongo = require("mongodb");
const MessageRepo = require("./lib/repos/MessageRepo");
const utils = require("./lib/utils");
const isSingleLine = conf.style == "single-line";
const PRIVATE_PREFIX = "_private";
let messageRepo;
let client = nats.connect({
servers: [conf.bus]
});
log.info("Connecting to NATS bus", conf.bus);
client.on("connect", () => {
log.info("Successfully connected to NATS bus", conf.bus);
health.start();
if (conf.mongoUrl) {
createMessageRepo(conf.mongoUrl).then(_messageRepo => {
messageRepo = _messageRepo;
});
}
client.subscribe(conf.logSubject, (msg, reply, subject) => {
if (
(conf.excludePattern && matchesPattern(subject, conf.excludePattern)) ||
subject.indexOf(PRIVATE_PREFIX) === 0
) {
return;
}
if (msg) {
let anonymizedJson = utils.anonymizeMessage(toJSON(msg));
log.debug(`[${formatSubject(subject)}] ${isSingleLine ? "" : "\n"}${prettyPrintJSON(anonymizedJson)}`);
if (messageRepo) {
messageRepo.save(subject, anonymizedJson);
}
}
});
});
client.on("error", function(e) {
log.error("Error [" + client.options.url + "]: " + e);
});
function createMessageRepo(mongoUrl) {
return mongo.connect(mongoUrl).then(db => {
log.info("Successfully connected to database");
return new MessageRepo(db);
});
}
function matchesPattern(str, pattern) {
if (pattern.indexOf("*") > -1) {
return new RegExp("^" + pattern.split("*").join(".*") + "$").test(str);
} else {
return str == pattern.trim();
}
}
function toJSON(str) {
try {
return JSON.parse(str);
} catch (e) {
return {};
}
}
function prettyPrintJSON(json) {
return JSON.stringify(json, null, isSingleLine ? 0 : 2);
}
function formatSubject(subject) {
return utils.isResponse(subject) ? "Response (" + subject + ")" : subject;
}