trace.js
2.72 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* 跟踪监控工具, 将监控数据写入influxdb
*
* @author: jiangfeng<jeff.jiang@yoho.cn>
* @date: 16/8/1
*/
'use strict';
const dgram = require('dgram');
const influx = require('influx');
const _ = require('lodash');
class Trace {
/**
* influxdb connection config
*
* @param options
*/
constructor(options) {
this.options = options;
}
report(name, keys, data) {
if (this.options.appName) {
keys.appName = this.options.appName;
}
let line = `${this._escape(name)},${this._makeLine(keys, false)} ${this._makeLine(data, true)}`;
return this._send(line);
}
/**
* make the data with influxdb's line protocol.
* @see https://docs.influxdata.com/influxdb/v0.13/write_protocols/line/
*
* @param data {object}
* @param withNoQuote {boolean}
* @returns {string}
* @private
*/
_makeLine(data, withNoQuote) {
if (_.isObject(data)) {
return Object.keys(data).map(key => {
return key + '=' + this._escape(data[key], withNoQuote);
}).join(',');
} else if (_.isArray(data)) {
return data.map(d => {
return this._makeLine(d, escape);
}).join(' ');
} else if (!_.isNil(data)) {
return 'value=' + this._escape(data, withNoQuote);
} else {
return '';
}
}
/**
* upd send.
* @param line {string} @see infulxdb's line protocol
* @returns {Promise}
* @private
*/
_send(line) {
let self = this;
return new Promise((resolve, reject) => {
let socket = dgram.createSocket('udp4');
let buff = new Buffer(line);
socket.send(buff, 0, buff.length, self.options.port, self.options.host, (err) => {
socket.close();
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
_escape(value, withQuote) {
if (_.isString(value)) {
if (withQuote) {
value = '"' + value + '"';
} else {
value = _.replace(value, /,/g, '\\,');
value = _.replace(value, /=/g, '\\=');
value = _.replace(value, /\s/g, '\\ ');
}
} else if (_.isInteger(value)) {
if (withQuote) {
value = value;
}
} else if (_.isObject(value)) {
value = '"' + _.replace(JSON.stringify(value), /"/g, '\\"') + '"';
} else if (_.isNull(value) || _.isNil(value)) {
value = '""';
}
return value;
}
}
module.exports = Trace;