forked from appium/appium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogsink.js
225 lines (196 loc) · 5.71 KB
/
logsink.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import npmlog from 'npmlog';
import { createLogger, format, transports } from 'winston';
import { fs, logger } from 'appium-support';
import _ from 'lodash';
// set up distributed logging before everything else
logger.patchLogger(npmlog);
global._global_npmlog = npmlog;
// npmlog is used only for emitting, we use winston for output
npmlog.level = 'silent';
const levels = {
debug: 4,
info: 3,
warn: 2,
error: 1,
};
const colors = {
info: 'cyan',
debug: 'grey',
warn: 'yellow',
error: 'red',
};
const npmToWinstonLevels = {
silly: 'debug',
verbose: 'debug',
debug: 'debug',
info: 'info',
http: 'info',
warn: 'warn',
error: 'error',
};
let log = null;
let useLocalTimeZone = false;
// add the timestamp in the correct format to the log info object
const timestampFormat = format.timestamp({
format () {
let date = new Date();
if (useLocalTimeZone) {
date = new Date(date.valueOf() - date.getTimezoneOffset() * 60000);
}
// '2012-11-04T14:51:06.157Z' -> '2012-11-04 14:51:06:157'
return date.toISOString()
.replace(/[TZ]/g, ' ')
.replace(/\./g, ':')
.trim();
},
});
// set the custom colors
const colorizeFormat = format.colorize({
colors,
});
// Strip the color marking within messages
const stripColorFormat = format(function stripColor (info) {
const code = /\u001b\[(\d+(;\d+)*)?m/g; // eslint-disable-line no-control-regex
info.message = info.message.replace(code, '');
return info;
})();
function createConsoleTransport (args, logLvl) {
return new (transports.Console)({
name: 'console',
handleExceptions: true,
exitOnError: false,
json: false,
level: logLvl,
stderrLevels: ['error'],
format: format.combine(
format(function adjustDebug (info) {
// prepend debug marker, and shift to `info` log level
if (info.level === 'debug') {
info.level = 'info';
info.message = `[debug] ${info.message}`;
}
return info;
})(),
timestampFormat,
args.logNoColors ? stripColorFormat : colorizeFormat,
format.printf(function printInfo (info) {
return `${args.logTimestamp ? `${info.timestamp} - ` : ''}${info.message}`;
})
),
});
}
function createFileTransport (args, logLvl) {
return new (transports.File)({
name: 'file',
filename: args.logFile,
maxFiles: 1,
handleExceptions: true,
exitOnError: false,
json: false,
level: logLvl,
format: format.combine(
stripColorFormat,
timestampFormat,
format.printf(function printInfo (info) {
return `${info.timestamp} ${info.message}`;
})
)
});
}
function createHttpTransport (args, logLvl) {
let host = '127.0.0.1';
let port = 9003;
if (args.webhook.match(':')) {
const hostAndPort = args.webhook.split(':');
host = hostAndPort[0];
port = parseInt(hostAndPort[1], 10);
}
return new (transports.Http)({
name: 'http',
host,
port,
path: '/',
handleExceptions: true,
exitOnError: false,
json: false,
level: logLvl,
format: format.combine(
stripColorFormat,
format.printf(function printInfo (info) {
return `${info.timestamp} ${info.message}`;
})
),
});
}
async function createTransports (args) {
let transports = [];
let consoleLogLevel = null;
let fileLogLevel = null;
if (args.loglevel && args.loglevel.match(':')) {
// --log-level arg can optionally provide diff logging levels for console and file, separated by a colon
const lvlPair = args.loglevel.split(':');
consoleLogLevel = lvlPair[0] || consoleLogLevel;
fileLogLevel = lvlPair[1] || fileLogLevel;
} else {
consoleLogLevel = fileLogLevel = args.loglevel;
}
transports.push(createConsoleTransport(args, consoleLogLevel));
if (args.logFile) {
try {
// if we don't delete the log file, winston will always append and it will grow infinitely large;
// winston allows for limiting log file size, but as of 9.2.14 there's a serious bug when using
// maxFiles and maxSize together. https://github.com/flatiron/winston/issues/397
if (await fs.exists(args.logFile)) {
await fs.unlink(args.logFile);
}
transports.push(createFileTransport(args, fileLogLevel));
} catch (e) {
// eslint-disable-next-line no-console
console.log(`Tried to attach logging to file '${args.logFile}' but an error ` +
`occurred: ${e.message}`);
}
}
if (args.webhook) {
try {
transports.push(createHttpTransport(args, fileLogLevel));
} catch (e) {
// eslint-disable-next-line no-console
console.log(`Tried to attach logging to Http at ${args.webhook} but ` +
`an error occurred: ${e.message}`);
}
}
return transports;
}
async function init (args) {
// set de facto param passed to timestamp function
useLocalTimeZone = args.localTimezone;
// clean up in case we have initiated before since npmlog is a global object
clear();
log = createLogger({
transports: await createTransports(args),
levels,
});
// Capture logs emitted via npmlog and pass them through winston
npmlog.on('log', (logObj) => {
const winstonLevel = npmToWinstonLevels[logObj.level] || 'info';
let msg = logObj.message;
if (logObj.prefix) {
const prefix = `[${logObj.prefix}]`;
msg = `${args.logNoColors ? prefix : prefix.magenta} ${msg}`;
}
log[winstonLevel](msg);
if (args.logHandler && _.isFunction(args.logHandler)) {
args.logHandler(logObj.level, msg);
}
});
}
function clear () {
if (log) {
for (let transport of _.keys(log.transports)) {
log.remove(transport);
}
}
npmlog.removeAllListeners('log');
}
export { init, clear };
export default init;