@tramvai/module-metrics 1.53.4 → 1.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -92
- package/package.json +9 -9
package/README.md
CHANGED
|
@@ -1,10 +1,73 @@
|
|
|
1
|
-
|
|
1
|
+
# @tramvai/module-metrics
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Module provides the interface described in `@platform/metrics-types`. On server the interface is implemented with public package `prom-client` that provides metrics on url `/metrics` Prometheus format.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
More details about metrics type, parameters and how to use it see in [docs to `prom-client`](https://github.com/siimon/prom-client).
|
|
6
6
|
|
|
7
|
-
##
|
|
7
|
+
## Explanation
|
|
8
|
+
|
|
9
|
+
### Monitoring outgoing requests
|
|
10
|
+
|
|
11
|
+
To monitor the state of the outgoing requests (like number of requests, number of error, time execution) the module monkey-patches `request` and `get` methods of the standard modules `http` and `https`. To make it work just add metrics module to the app.
|
|
12
|
+
|
|
13
|
+
Next labels are added to metrics:
|
|
14
|
+
|
|
15
|
+
- http method
|
|
16
|
+
- http response code
|
|
17
|
+
- service name
|
|
18
|
+
|
|
19
|
+
Name of the service calculates by comparing request urls with values in `MetricsServicesRegistry`. Initially the register is bootstrapped with the inverted content of env variables, e.g. if some url from env is a substring of the request url, then the name of the env become the service name. If several envs matches this logic then the env with the longest url is used.
|
|
20
|
+
|
|
21
|
+
### Client metrics
|
|
22
|
+
|
|
23
|
+
Module implements feature to collect metrics from the clients and share it with Prometheus by sending metrics from the client to server papi-route.
|
|
24
|
+
|
|
25
|
+
Metrics module can help in implementing this functionality in common cases. To create metric register provider for the token `REGISTER_INSTANT_METRIC_TOKEN`. Your provider should return list of two entities - first is a slug of papi-route and second is an instance of Counter. E.g.:
|
|
26
|
+
|
|
27
|
+
```javascript
|
|
28
|
+
import { provide } from '@tramvai/core';
|
|
29
|
+
|
|
30
|
+
provide({
|
|
31
|
+
provide: REGISTER_INSTANT_METRIC_TOKEN,
|
|
32
|
+
multi: true,
|
|
33
|
+
deps: {
|
|
34
|
+
metrics: METRICS_MODULE_TOKEN,
|
|
35
|
+
},
|
|
36
|
+
useFactory({ metrics }) {
|
|
37
|
+
return ['page-load', new Counter({ name: 'client_page_load_total', help: 'Client page load' })];
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
After that to increment metric `client_page_load_total` you can call papi-route `/metrics/page-load`.
|
|
43
|
+
|
|
44
|
+
#### instantMetricsReporter
|
|
45
|
+
|
|
46
|
+
In practice it become clear that besides metric collection it often needed to collect logs with details. This can be implemented with `instantMetricsReporter`. When calling logger module will check that any metric with the slug equal to the event of the log is exist. If so module will send request to the corresponding papi-route.
|
|
47
|
+
|
|
48
|
+
Next way you can log event and increment server metric:
|
|
49
|
+
|
|
50
|
+
```javascript
|
|
51
|
+
import { provide } from '@tramvai/core';
|
|
52
|
+
provide({
|
|
53
|
+
provide: commandLineListTokens.init,
|
|
54
|
+
multi: true,
|
|
55
|
+
deps: {
|
|
56
|
+
logger: LOGGER_TOKEN,
|
|
57
|
+
},
|
|
58
|
+
useFactory({ logger }) {
|
|
59
|
+
return () => {
|
|
60
|
+
window.on('load', () => {
|
|
61
|
+
logger.info({ event: 'page-load' });
|
|
62
|
+
})
|
|
63
|
+
};
|
|
64
|
+
},
|
|
65
|
+
}),
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## How to
|
|
69
|
+
|
|
70
|
+
### Usage Example
|
|
8
71
|
|
|
9
72
|
```tsx
|
|
10
73
|
import { createToken } from '@tinkoff/dippy';
|
|
@@ -48,121 +111,55 @@ export const SOME_MODULE = createToken<SomeModule>('someModule');
|
|
|
48
111
|
export class SomeModuleContainer {}
|
|
49
112
|
```
|
|
50
113
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
Для того чтобы мониторить состояние исходящих запросов (количество запросов, количество ошибок, время выполнения) в модуле манкипатчатся методы request и get модулей http и https. Чтобы это заработало необходимо просто подключить модуль метрик в приложение.
|
|
114
|
+
### Make service names showed in metrics instead of hostnames
|
|
54
115
|
|
|
55
|
-
|
|
116
|
+
It is possible to give a hint to module about the service name in case url is dynamic. To do that:
|
|
56
117
|
|
|
57
|
-
-
|
|
58
|
-
-
|
|
59
|
-
- имя сервиса
|
|
118
|
+
- use token `METRICS_SERVICES_REGISTRY_TOKEN`;
|
|
119
|
+
- call `metricsServicesRegistry.register("Part of the url or the whole url", "Name of service")`
|
|
60
120
|
|
|
61
|
-
|
|
121
|
+
### Use metrics to profile performance in browser
|
|
62
122
|
|
|
63
|
-
|
|
123
|
+
To measure length of the events you must use method `startTimer` of classes Gauge, Histogram, Summary. In dev-mode these classes are patched and methods to work with timers will use [PerformanceApi](https://developer.mozilla.org/en-US/docs/Web/API/Performance).
|
|
64
124
|
|
|
65
|
-
|
|
125
|
+
Example without additional fields:
|
|
66
126
|
|
|
67
|
-
|
|
68
|
-
- вызвать `metricsServicesRegistry.register("Часть урла или весь урл", "Имя сервиса")`
|
|
69
|
-
|
|
70
|
-
## Использование метрик для профилирования перформанса на стороне браузера
|
|
71
|
-
|
|
72
|
-
Для измерения продолжительности события, необходимо использовать метод `startTimer` у классов Gauge, Histogram и Summary. В dev-режиме эти классы патчатся и методы работы с таймером использует [PerformanceApi](https://developer.mozilla.org/en-US/docs/Web/API/Performance).
|
|
73
|
-
|
|
74
|
-
## Пример использования
|
|
75
|
-
|
|
76
|
-
Без дополнительных полей
|
|
77
|
-
|
|
78
|
-
```
|
|
127
|
+
```ts
|
|
79
128
|
const metric = metrics.gauge({
|
|
80
|
-
|
|
81
|
-
|
|
129
|
+
name: 'request_measure',
|
|
130
|
+
help: 'Request duration measure',
|
|
82
131
|
});
|
|
83
132
|
|
|
84
133
|
const endTimer = metric.startTimer();
|
|
85
134
|
|
|
86
135
|
fetch(url).then(() => {
|
|
87
|
-
|
|
136
|
+
endTimer();
|
|
88
137
|
|
|
89
|
-
|
|
138
|
+
// output the result - performance.getEntriesByName('request_measure');
|
|
90
139
|
});
|
|
91
140
|
```
|
|
92
141
|
|
|
93
|
-
|
|
142
|
+
Example with adding dynamic fields:
|
|
94
143
|
|
|
95
|
-
```
|
|
144
|
+
```ts
|
|
96
145
|
const metric = metrics.gauge({
|
|
97
|
-
|
|
98
|
-
|
|
146
|
+
name: 'request_measure',
|
|
147
|
+
help: 'Request duration measure',
|
|
99
148
|
});
|
|
100
149
|
|
|
101
150
|
const endTimer = metric.startTimer({ method: 'GET' });
|
|
102
151
|
|
|
103
152
|
fetch(url).then(() => {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
// выводим результат - performance.getEntriesByName('request_measure{method="GET",status="200"}');
|
|
107
|
-
});
|
|
108
|
-
```
|
|
109
|
-
|
|
110
|
-
## Клиентские метрики
|
|
111
|
-
|
|
112
|
-
Модуль реализует в себе возможность собирать метрики с клиента и раздавать их прометеусам с помощью обычного серверного механизма через отправку метрик в papi-роуты.
|
|
153
|
+
endTimer({ status: 200 });
|
|
113
154
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
В модуле уже реализован весь общий для таких случаев функционал. Чтобы создать метрику необходимо создать провайдер с токеном `REGISTER_INSTANT_METRIC_TOKEN`, провайдер должен возвращать список из двух сущностей где первая это slug papi-роута, а вторая это инстанс счётчика. Например:
|
|
117
|
-
|
|
118
|
-
```javascript
|
|
119
|
-
import { provide } from '@tramvai/core';
|
|
120
|
-
|
|
121
|
-
provide({
|
|
122
|
-
provide: REGISTER_INSTANT_METRIC_TOKEN,
|
|
123
|
-
multi: true,
|
|
124
|
-
deps: {
|
|
125
|
-
metrics: METRICS_MODULE_TOKEN,
|
|
126
|
-
},
|
|
127
|
-
useFactory({ metrics }) {
|
|
128
|
-
return [
|
|
129
|
-
'page-load',
|
|
130
|
-
new Counter({ name: 'client_page_load_total', help: 'Загрузки страниц у клиентов' }),
|
|
131
|
-
];
|
|
132
|
-
},
|
|
155
|
+
// output the result - performance.getEntriesByName('request_measure{method="GET",status="200"}');
|
|
133
156
|
});
|
|
134
157
|
```
|
|
135
158
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
#### instantMetricsReporter
|
|
139
|
-
|
|
140
|
-
На практике выяснилось что часто помимо сбора метрик необходимо отправить логи с подробностями. Эту потребность реализует instantMetricsReporter. При вызове логгера он проверяет наличие метрик со slug аналогичным полю event в логах и если такие метрики существуют, то отправляет запрос на соответствующий papi-роут.
|
|
141
|
-
|
|
142
|
-
Таким образом можно одновременно залогировать событие и инкрементировать серверную метрику.
|
|
143
|
-
|
|
144
|
-
```javascript
|
|
145
|
-
import { provide } from '@tramvai/core';
|
|
146
|
-
provide({
|
|
147
|
-
provide: commandLineListTokens.init,
|
|
148
|
-
multi: true,
|
|
149
|
-
deps: {
|
|
150
|
-
logger: LOGGER_TOKEN,
|
|
151
|
-
},
|
|
152
|
-
useFactory({ logger }) {
|
|
153
|
-
return () => {
|
|
154
|
-
window.on('load', () => {
|
|
155
|
-
logger.info({ event: 'page-load' });
|
|
156
|
-
})
|
|
157
|
-
};
|
|
158
|
-
},
|
|
159
|
-
}),
|
|
160
|
-
```
|
|
161
|
-
|
|
162
|
-
## Отладка
|
|
159
|
+
## Debug
|
|
163
160
|
|
|
164
|
-
|
|
161
|
+
The module uses loggers with the next ids: `metrics:perf`, `metrics:papi`
|
|
165
162
|
|
|
166
|
-
##
|
|
163
|
+
## Exported tokens
|
|
167
164
|
|
|
168
|
-
[
|
|
165
|
+
[link](references/tokens/metrics-tokens.md)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tramvai/module-metrics",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.55.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"browser": "lib/browser.js",
|
|
6
6
|
"main": "lib/server.js",
|
|
@@ -19,19 +19,19 @@
|
|
|
19
19
|
"build-for-publish": "true"
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@tramvai/core": "1.
|
|
23
|
-
"@tramvai/tokens-server": "1.
|
|
24
|
-
"@tramvai/tokens-metrics": "1.
|
|
25
|
-
"@tramvai/module-common": "1.
|
|
26
|
-
"@tramvai/tokens-http-client": "1.
|
|
27
|
-
"@tramvai/state": "1.
|
|
28
|
-
"@tramvai/papi": "1.
|
|
22
|
+
"@tramvai/core": "1.55.0",
|
|
23
|
+
"@tramvai/tokens-server": "1.55.0",
|
|
24
|
+
"@tramvai/tokens-metrics": "1.55.0",
|
|
25
|
+
"@tramvai/module-common": "1.55.0",
|
|
26
|
+
"@tramvai/tokens-http-client": "1.55.0",
|
|
27
|
+
"@tramvai/state": "1.55.0",
|
|
28
|
+
"@tramvai/papi": "1.55.0",
|
|
29
29
|
"@tinkoff/measure-express-requests": "1.4.2",
|
|
30
30
|
"@tinkoff/monkeypatch": "1.3.3",
|
|
31
31
|
"@tinkoff/url": "0.7.37",
|
|
32
32
|
"@tinkoff/utils": "^2.1.2",
|
|
33
33
|
"prom-client": "^12.0.0",
|
|
34
|
-
"@tinkoff/logger": "0.10.
|
|
34
|
+
"@tinkoff/logger": "0.10.13",
|
|
35
35
|
"@tinkoff/metrics-noop": "1.0.2",
|
|
36
36
|
"@tinkoff/browser-timings": "0.9.4",
|
|
37
37
|
"express": "^4.17.1"
|