-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (76 loc) · 2.75 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
'use strict';
function timed(promise) {
const timeDelta = (d1, d2) => d2.valueOf() - d1.valueOf();
return Promise.resolve(new Date())
.then(startTime => {
return Promise.resolve(promise)
.then(result => [timeDelta(startTime, new Date()), result])
.catch(err => {
const newErr = {
name: 'Timed error',
message: 'Error thrown in timed promise',
duration: timeDelta(startTime, new Date()),
reason: err
};
throw newErr;
});
});
}
module.exports = (logFn, baseName) =>
() => {
const collected = {
measure: {},
count: {},
sample: {}
};
const formatMetrics = () => Object
.keys(collected)
.map(type =>
Object.keys(collected[type])
.map(k => `${type}#${baseName}.${k}=${collected[type][k]}`)
.join(' '))
.join(' ');
const metrics = {
dropToLogs: () => {
logFn(formatMetrics());
return metrics;
},
sample: (name, metricProducer, promise) => {
return Promise.resolve(promise).then(v => {
collected.sample[name] = metricProducer(v);
return v;
});
},
measure: (name, metricProducer, promise) => {
return Promise.resolve(promise).then(v => {
collected.measure[name] = metricProducer(v);
return v;
});
},
increment: (name, incrValueProducer, promise) => {
return Promise.resolve(promise).then(v => {
collected.count[name] = incrValueProducer(v);
return v;
});
},
incrementByOne: (name) => {
return Promise.resolve()
.then(() => {
collected.count[name] = (collected.count[name] || 0) + 1;
return collected.count[name];
})
},
timed: (name, promise) => {
return timed(promise)
.then(([duration, result]) => {
collected.measure[`${name}.success_duration`] = duration;
return result;
})
.catch((err) => {
collected.measure[`${name}.error_duration`] = err.duration;
throw err.reason || err;
});
}
};
return metrics;
};