forked from tapd8/apig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog4js-http.js
77 lines (62 loc) · 1.62 KB
/
log4js-http.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
/**
* @author lg<[email protected]>
* @date 4/20/19
* @description
*/
'use strict';
const util = require('util');
const request = require('request');
const pid = process.pid;
function wrapErrorsWithInspect(items) {
return items.map((item) => {
if ((item instanceof Error) && item.stack) {
return {
inspect: function () {
return `${util.format(item)}\n${item.stack}`;
}
};
}
return item;
});
}
function format(logData) {
return util.format.apply(util, wrapErrorsWithInspect(logData));
}
function logFacesAppender(config) {
return function log(event) {
const {getToken, removeToken} = require('./tapdata');
// convert to logFaces compact json format
const lfsEvent = {
threadId: pid,
threadName: config.application || '', // application name
date: event.startTime.getTime(), // time stamp
level: event.level.levelStr, // level (priority)
loggerName: event.categoryName, // logger name
message: format(event.data) // message text
};
// add context variables if exist
Object.keys(event.context).forEach((key) => {
lfsEvent[`p_${key}`] = event.context[key];
});
// send to server
getToken(function(token){
let url = config.url + '?access_token=' + token;
request.post({
url: url,
json: true,
body: lfsEvent
}, (err, resp, body) => {
if( err ){
console.error('report fail', err);
} else if(resp.statusCode === 401 || resp.statusCode === 403) {
console.error('Access token Expired');
removeToken();
}
});
});
};
}
function configure(config) {
return logFacesAppender(config);
}
module.exports.configure = configure;