-
Notifications
You must be signed in to change notification settings - Fork 1
/
logs.js
executable file
·104 lines (90 loc) · 2.55 KB
/
logs.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
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
#!/usr/bin/env node
//
// Logs.js
// Connect to the running containers and pipe their logs to the console.
//
const async = require("async");
const os = require("os");
const shell = require("shelljs");
const { spawn } = require("child_process");
var stdout = null;
if (os.platform() == "win32") {
// windows method of gathering the service names:
stdout = shell
.exec(
`for /f "tokens=2" %a in ('docker service ls ^| findstr "ab_" ') do @echo %a`
)
.stdout.replace(/\r/g, "");
} else {
// common unix method of gathering the service names:
stdout = shell.exec(`docker service ls | grep "ab_" | awk '{ print $2 }'`)
.stdout;
}
var allServiceIDs = stdout.split("\n");
var allServices = {};
var maxIDLength = -10;
var closeDown = (signal) => {
// our process exit handler
// be sure to kill all our sub processes
allServiceIDs.forEach((id) => {
if (allServices[id]) {
console.log(`closing logger(${id}) with ${signal}`);
allServices[id].kill(signal);
}
});
};
function pad(text, length) {
while (text.length < length) {
text += " ";
}
return text;
}
function cleanText(id, text) {
var lines = text.split("\n");
var output = [];
lines.forEach((line) => {
if (line.length > 0) {
var parts = line.split("|");
if (parts.length > 1) {
parts.shift();
}
output.push(`${pad(id, maxIDLength)} : ${parts.join("|")}`);
}
});
return output.join("\n");
}
async.eachSeries(
allServiceIDs,
(id, cb) => {
if (id == "") {
cb();
return;
}
// create a new process for logging the given service id
var options = ["service", "logs", "-f", "--tail", "50", id]; // `docker service logs -f ${id}`;
var logger = spawn("docker", options, {
// stdio: ["ignore", "ignore", "ignore"]
});
logger.stdout.on("data", (data) => {
console.log(cleanText(id, data.toString()));
});
logger.stderr.on("data", (data) => {
console.error(cleanText(id, data.toString()));
});
if (id.length > maxIDLength) {
maxIDLength = id.length;
}
allServices[id] = logger;
cb();
},
(err) => {
if (err) {
console.error(err);
console.log();
closeDown("SIGINT");
process.exit();
}
}
);
process.on("SIGINT", closeDown);
process.on("SIGTERM", closeDown);