This repository has been archived by the owner on Mar 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
196 lines (164 loc) · 5.19 KB
/
index.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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
'use strict'
const merge = require('lodash.merge');
const defaults = require('merge-defaults');
const express = require('express');
const winston = require('winston');
const common = require('winston/lib/winston/common');
const cycle = require('cycle');
const expressWinston = require('express-winston');
const fs = require('fs');
function createLogFormatter(appname, lastcommit, version) {
return function logFormatter(log) {
const timestamp = common.timestamp();
const logstashOutput = {
lastcommit,
version,
appname
};
const meta = common.clone(cycle.decycle(log.meta)) || {};
const baseLog = {
message: log.message
};
let msg = log.message;
if (typeof msg !== 'string') {
msg = '' + msg;
}
if (msg !== undefined && msg !== null) {
logstashOutput['message'] = msg;
}
logstashOutput['@timestamp'] = timestamp;
logstashOutput['level'] = log.level;
logstashOutput['X-B3-TraceId'] = meta['X-B3-TraceId'];
logstashOutput['fields'] = merge(baseLog, meta);
return JSON.stringify(logstashOutput);
}
}
/**
* options -> {
* basePath: String,
* heatlhCheckInfo: Function,
* autoStart: Boolean
* }
*
* Returns base app + configured logger
*/
module.exports = function(applicationName, opts) {
const app = express();
const options = defaults(opts, {
healthCheckInfo: function() {},
autoStart: true
});
const config = require('./config.json');
let lastCommit;
let version;
try {
const userConfig = require(`${options.basePath}/config.json`);
config = merge(config, userConfig);
} catch (e) {}
try {
const systemConfig = require(`/usr/local/honestica/${applicationName}/config.json`);
config = merge(config, systemConfig);
} catch(e) {}
try {
const build = require(`${options.basePath}/build.json`);
lastCommit = build.lastcommit;
version = build.version;
} catch(e) {}
// setup logs
if (!config.logs) {
throw new Error('Need logs params in config');
}
const transports = [ ];
if (config.logs.console) {
transports.push(
new winston.transports.Console({
colorize: true,
timestamp: true,
formatter: config.logs.logstash ? createLogFormatter(applicationName, lastCommit, version) : undefined,
json: false,
handleExceptions: true,
humanReadableUnhandledException: true
})
);
}
if (config.logs.file) {
transports.push(new winston.transports.File({
filename: config.logs.file,
json: false,
formatter: config.logs.logstash ? createLogFormatter(applicationName, lastCommit, version) : undefined,
handleExceptions: true,
humanReadableUnhandledException: true
}));
}
const myCustomLevels = {
levels: {
ERROR: 0,
WARN: 1,
INFO: 2,
VERBOSE: 3,
DEBUG: 4,
SILLY: 5
},
colors: {
ERROR: 'blue',
WARN: 'green',
INFO: 'green',
VERBOSE: 'green',
DEBUG: 'red',
SILLY: 'red'
}
};
const logger = new winston.Logger({
transports: transports,
levels: myCustomLevels.levels,
level: 'INFO'
});
winston.addColors(myCustomLevels.colors);
app.use(expressWinston.logger({
transports: transports,
meta: true,
msg: "HTTP {{req.method}} {{req.url}}",
expressFormat: true,
colorStatus: true
}));
//start server
if (!config.port) {
throw new Error('No port found in config file');
}
if (options.autoStart) {
app.listen(config.port, function () {
logger.INFO(`${applicationName} started on port ${config.port}`);
}).on('error', (log) => logger.ERROR(log));
}
// health check
if (config.healthCheck) {
const callback = function (req, res) {
const method = req.method;
// accept head and get
if (!(method === 'HEAD' || method === 'GET')) {
return res.sendStatus(405);
}
// read health check file
fs.readFile(config.healthCheck, 'utf8', function (err, data) {
if (err) {
logger.ERROR('Health check file not found');
return res.sendStatus(500);
}
if (data.trim() !== 'IN') {
return res.sendStatus(503);;
} else {
return res.send({
uptime: process.uptime(),
name: applicationName,
version: version,
lastcommit: lastCommit,
app: options.healthCheckInfo()
});
}
});
};
app.all('/admin/health', callback);
app.all(`/${applicationName}/admin/health`, callback);
}
return { app, logger, config };
}