1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('../base/Component');
|
7 |
|
8 | module.exports = class ActionProfiler extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | level: 'debug',
|
13 | threshold: 0,
|
14 | logger: 'logger',
|
15 | ...config
|
16 | });
|
17 | }
|
18 |
|
19 | init () {
|
20 | this.logger = this.module.get(this.logger);
|
21 | if (this.logger.getType(this.level)) {
|
22 | this.module.addHandler('use', this.start);
|
23 | this.module.on(this.module.EVENT_AFTER_ACTION, this.end.bind(this));
|
24 | }
|
25 | }
|
26 |
|
27 | start (req, res, next) {
|
28 | res.locals.startActionTimeProfiler = Date.now();
|
29 | next();
|
30 | }
|
31 |
|
32 | end (event) {
|
33 | const controller = event.action.controller;
|
34 | const time = Date.now() - controller.res.locals.startActionTimeProfiler;
|
35 | if (time >= this.threshold) {
|
36 | this.logger.log(this.level, this.formatTime(time, controller));
|
37 | }
|
38 | }
|
39 |
|
40 | formatTime (time, controller) {
|
41 | return `${controller.response.code} ${controller.req.method} ${time} ms ${controller.getOriginalUrl()}`;
|
42 | }
|
43 | }; |
\ | No newline at end of file |