UNPKG

7.83 kBJavaScriptView Raw
1"use strict";
2/********************************************************************************
3* Copyright (c) 2021 STMicroelectronics and others.
4*
5* This program and the accompanying materials are made available under the
6* terms of the Eclipse Public License 2.0 which is available at
7* http://www.eclipse.org/legal/epl-2.0.
8*
9* This Source Code may also be made available under the following Secondary
10* Licenses when the conditions for such availability set forth in the Eclipse
11* Public License v. 2.0 are satisfied: GNU General Public License, version 2
12* with the GNU Classpath Exception which is available at
13* https://www.gnu.org/software/classpath/license.html.
14*
15* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
16*******************************************************************************/
17var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
18 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
19 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
20 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
21 return c > 3 && r && Object.defineProperty(target, key, r), r;
22};
23var __metadata = (this && this.__metadata) || function (k, v) {
24 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
25};
26Object.defineProperty(exports, "__esModule", { value: true });
27exports.Stopwatch = void 0;
28/* eslint-disable @typescript-eslint/no-explicit-any */
29const inversify_1 = require("inversify");
30const logger_1 = require("../logger");
31const event_1 = require("../event");
32/** The default log level for measurements that are not otherwise configured with a default. */
33const DEFAULT_LOG_LEVEL = logger_1.LogLevel.INFO;
34/**
35 * A factory of {@link Measurement}s for performance logging.
36 */
37let Stopwatch = class Stopwatch {
38 constructor(defaultLogOptions) {
39 this.defaultLogOptions = defaultLogOptions;
40 this._storedMeasurements = [];
41 this.onDidAddMeasurementResultEmitter = new event_1.Emitter();
42 if (!defaultLogOptions.defaultLogLevel) {
43 defaultLogOptions.defaultLogLevel = DEFAULT_LOG_LEVEL;
44 }
45 if (defaultLogOptions.storeResults === undefined) {
46 defaultLogOptions.storeResults = true;
47 }
48 }
49 get onDidAddMeasurementResult() {
50 return this.onDidAddMeasurementResultEmitter.event;
51 }
52 /**
53 * Wrap an asynchronous function in a {@link Measurement} that logs itself on completion.
54 * If obtaining and awaiting the `computation` runs too long according to the threshold
55 * set in the `options`, then the log message is a warning, otherwise a debug log.
56 *
57 * @param name the {@link Measurement.name name of the measurement} to wrap around the function
58 * @param description a description of what the function does, to be included in the log
59 * @param computation a supplier of the asynchronous function to wrap
60 * @param options optional addition configuration as for {@link measure}
61 * @returns the wrapped `computation`
62 *
63 * @see {@link MeasurementOptions.thresholdMillis}
64 */
65 async startAsync(name, description, computation, options) {
66 var _a;
67 const threshold = (_a = options === null || options === void 0 ? void 0 : options.thresholdMillis) !== null && _a !== void 0 ? _a : Number.POSITIVE_INFINITY;
68 const measure = this.start(name, options);
69 const result = await computation();
70 if (measure.stop() > threshold) {
71 measure.warn(`${description} took longer than the expected maximum ${threshold} milliseconds`);
72 }
73 else {
74 measure.log(description);
75 }
76 return result;
77 }
78 createMeasurement(name, measure, options) {
79 const logOptions = this.mergeLogOptions(options);
80 const measurement = {
81 name,
82 stop: () => {
83 if (measurement.elapsed === undefined) {
84 const { startTime, duration } = measure();
85 measurement.elapsed = duration;
86 const result = {
87 name,
88 elapsed: duration,
89 startTime,
90 owner: logOptions.owner
91 };
92 if (logOptions.storeResults) {
93 this._storedMeasurements.push(result);
94 }
95 this.onDidAddMeasurementResultEmitter.fire(result);
96 }
97 return measurement.elapsed;
98 },
99 log: (activity, ...optionalArgs) => this.log(measurement, activity, this.atLevel(logOptions, undefined, optionalArgs)),
100 debug: (activity, ...optionalArgs) => this.log(measurement, activity, this.atLevel(logOptions, logger_1.LogLevel.DEBUG, optionalArgs)),
101 info: (activity, ...optionalArgs) => this.log(measurement, activity, this.atLevel(logOptions, logger_1.LogLevel.INFO, optionalArgs)),
102 warn: (activity, ...optionalArgs) => this.log(measurement, activity, this.atLevel(logOptions, logger_1.LogLevel.WARN, optionalArgs)),
103 error: (activity, ...optionalArgs) => this.log(measurement, activity, this.atLevel(logOptions, logger_1.LogLevel.ERROR, optionalArgs)),
104 };
105 return measurement;
106 }
107 mergeLogOptions(logOptions) {
108 const result = { ...this.defaultLogOptions };
109 if (logOptions) {
110 Object.assign(result, logOptions);
111 }
112 return result;
113 }
114 atLevel(logOptions, levelOverride, optionalArgs) {
115 return { ...logOptions, levelOverride, arguments: optionalArgs };
116 }
117 logLevel(elapsed, options) {
118 var _a, _b;
119 if (options === null || options === void 0 ? void 0 : options.levelOverride) {
120 return options.levelOverride;
121 }
122 return (_b = (_a = options === null || options === void 0 ? void 0 : options.defaultLogLevel) !== null && _a !== void 0 ? _a : this.defaultLogOptions.defaultLogLevel) !== null && _b !== void 0 ? _b : DEFAULT_LOG_LEVEL;
123 }
124 log(measurement, activity, options) {
125 var _a;
126 const elapsed = measurement.stop();
127 const level = this.logLevel(elapsed, options);
128 if (Number.isNaN(elapsed)) {
129 switch (level) {
130 case logger_1.LogLevel.ERROR:
131 case logger_1.LogLevel.FATAL:
132 // Always log errors, even if NaN duration from native API preventing a measurement
133 break;
134 default:
135 // Measurement was prevented by native API, do not log NaN duration
136 return;
137 }
138 }
139 const start = options.owner ? `${options.owner} start` : 'start';
140 const timeFromStart = `Finished ${(options.now() / 1000).toFixed(3)} s after ${start}`;
141 const whatWasMeasured = options.context ? `[${options.context}] ${activity}` : activity;
142 this.logger.log(level, `${whatWasMeasured}: ${elapsed.toFixed(1)} ms [${timeFromStart}]`, ...((_a = options.arguments) !== null && _a !== void 0 ? _a : []));
143 }
144 get storedMeasurements() {
145 return this._storedMeasurements;
146 }
147};
148__decorate([
149 (0, inversify_1.inject)(logger_1.ILogger),
150 __metadata("design:type", Object)
151], Stopwatch.prototype, "logger", void 0);
152Stopwatch = __decorate([
153 (0, inversify_1.injectable)(),
154 __metadata("design:paramtypes", [Object])
155], Stopwatch);
156exports.Stopwatch = Stopwatch;
157//# sourceMappingURL=stopwatch.js.map
\No newline at end of file