Debian Codegraph @

addons/web/static/lib/hoot/core/logger.js

raw
1 /** @odoo-module */
2
3 import { getColorHex } from "../../hoot-dom/hoot_dom_utils";
4 import { isNil, stringify } from "../hoot_utils";
5 import { urlParams } from "./url";
6
7 //-----------------------------------------------------------------------------
8 // Global
9 //-----------------------------------------------------------------------------
10
11 const {
12 console: {
13 debug: $debug,
14 dir: $dir,
15 error: $error,
16 groupCollapsed: $groupCollapsed,
17 groupEnd: $groupEnd,
18 log: $log,
19 table: $table,
20 trace: $trace,
21 warn: $warn,
22 },
23 Object: { entries: $entries, getOwnPropertyDescriptors: $getOwnPropertyDescriptors },
24 } = globalThis;
25
26 //-----------------------------------------------------------------------------
27 // Internal
28 //-----------------------------------------------------------------------------
29
30 /**
31 * @param {any[]} args
32 * @param {string} [prefix]
33 * @param {string} [prefixColor]
34 */
35 function styledArguments(args, prefix, prefixColor) {
36 const fullPrefix = `%c[${prefix || DEFAULT_PREFIX[0]}]%c`;
37 const styles = [`color:${prefixColor || DEFAULT_PREFIX[1]};font-weight:bold`, ""];
38 const firstArg = args.shift() ?? "";
39 if (typeof firstArg === "string") {
40 args.unshift(`${fullPrefix} ${firstArg}`, ...styles);
41 } else {
42 args.unshift(fullPrefix, ...styles, firstArg);
43 }
44 return args;
45 }
46
47 /**
48 * @param {any[]} args
49 */
50 function unstyledArguments(args) {
51 const prefix = `[${DEFAULT_PREFIX[0]}]`;
52 const firstArg = args.shift() ?? "";
53 if (typeof firstArg === "string") {
54 args.unshift(`${prefix} ${firstArg}`);
55 } else {
56 args.unshift(prefix, firstArg);
57 }
58 return [args.join(" ")];
59 }
60
61 class Logger {
62 /** @private */
63 issueLevel;
64 /** @private */
65 logLevel;
66
67 constructor(logLevel, issueLevel) {
68 this.logLevel = logLevel;
69 this.issueLevel = issueLevel;
70
71 // Pre-bind all methods for ease of use
72 for (const [key, desc] of $entries($getOwnPropertyDescriptors(Logger.prototype))) {
73 if (key !== "constructor" && typeof desc.value === "function") {
74 this[key] = this[key].bind(this);
75 }
76 }
77 }
78
79 get global() {
80 return new Logger(this.logLevel, ISSUE_LEVELS.global);
81 }
82
83 // Standard console methods
84
85 /**
86 * @param {...any} args
87 */
88 debug(...args) {
89 $debug(...styledArguments(args));
90 }
91 /**
92 * @param {...any} args
93 */
94 error(...args) {
95 switch (this.issueLevel) {
96 case ISSUE_LEVELS.suppressed: {
97 $groupCollapsed(...styledArguments(["suppressed"], ...ERROR_PREFIX));
98 $trace(...args);
99 $groupEnd();
100 break;
101 }
102 case ISSUE_LEVELS.trace: {
103 $trace(...styledArguments(args, ...ERROR_PREFIX));
104 break;
105 }
106 case ISSUE_LEVELS.global: {
107 $error(...styledArguments(args));
108 break;
109 }
110 default: {
111 $error(...args);
112 break;
113 }
114 }
115 }
116 /**
117 * @param {any} arg
118 * @param {() => any} callback
119 */
120 group(title, callback) {
121 $groupCollapsed(...styledArguments([title]));
122 callback();
123 $groupEnd();
124 }
125 /**
126 * @param {...any} args
127 */
128 table(...args) {
129 $table(...args);
130 }
131 /**
132 * @param {...any} args
133 */
134 trace(...args) {
135 $trace(...args);
136 }
137 /**
138 * @param {...any} args
139 */
140 warn(...args) {
141 switch (this.issueLevel) {
142 case ISSUE_LEVELS.suppressed: {
143 $groupCollapsed(...styledArguments(["suppressed"], ...WARNING_PREFIX));
144 $trace(...args);
145 $groupEnd();
146 break;
147 }
148 case ISSUE_LEVELS.global: {
149 $warn(...styledArguments(args));
150 break;
151 }
152 default: {
153 $warn(...args);
154 break;
155 }
156 }
157 }
158
159 // Level-specific methods
160
161 /**
162 * @param {...any} args
163 */
164 logDebug(...args) {
165 if (!this.canLog("debug")) {
166 return;
167 }
168 $debug(...styledArguments(args, ...DEBUG_PREFIX));
169 }
170 /**
171 * @param {import("./suite").Suite} suite
172 */
173 logSuite(suite) {
174 if (!this.canLog("suites")) {
175 return;
176 }
177 const args = [`${stringify(suite.fullName)} ended`];
178 const withArgs = [];
179 if (suite.reporting.passed) {
180 withArgs.push("passed:", suite.reporting.passed, "/");
181 }
182 if (suite.reporting.failed) {
183 withArgs.push("failed:", suite.reporting.failed, "/");
184 }
185 if (suite.reporting.skipped) {
186 withArgs.push("skipped:", suite.reporting.skipped, "/");
187 }
188 if (withArgs.length) {
189 args.push(
190 `(${withArgs.shift()}`,
191 ...withArgs,
192 "time:",
193 suite.reporting.duration,
194 "ms)"
195 );
196 }
197 $log(...styledArguments(args));
198 }
199 /**
200 * @param {import("./test").Test} test
201 */
202 logTest(test) {
203 if (!this.canLog("tests")) {
204 return;
205 }
206 const { fullName, lastResults } = test;
207 $log(
208 ...styledArguments([
209 `Test ${stringify(fullName)} passed (assertions:`,
210 lastResults.counts.assertion || 0,
211 `/ time:`,
212 lastResults.duration,
213 `ms)`,
214 ])
215 );
216 }
217 /**
218 * @param {[label: string, color: string]} prefix
219 * @param {...any} args
220 */
221 logTestEvent(prefix, ...args) {
222 $log(...styledArguments(args, ...prefix));
223 }
224 /**
225 * @param {...any} args
226 */
227 logRun(...args) {
228 if (!this.canLog("runner")) {
229 return;
230 }
231 $log(...styledArguments(args));
232 }
233 /**
234 * @param {...any} args
235 */
236 logGlobal(...args) {
237 $dir(...unstyledArguments(args));
238 }
239
240 // Other methods
241
242 /**
243 * @param {keyof typeof LOG_LEVELS} level
244 */
245 canLog(level) {
246 return this.logLevel >= LOG_LEVELS[level];
247 }
248 /**
249 * @param {keyof typeof ISSUE_LEVELS} level
250 */
251 setIssueLevel(level) {
252 const restoreIssueLevel = () => {
253 this.issueLevel = previous;
254 };
255 const previous = this.issueLevel;
256 this.issueLevel = ISSUE_LEVELS[level];
257 return restoreIssueLevel;
258 }
259 /**
260 * @param {keyof typeof LOG_LEVELS} level
261 */
262 setLogLevel(level) {
263 const restoreLogLevel = () => {
264 this.logLevel = previous;
265 };
266 const previous = this.logLevel;
267 this.logLevel = LOG_LEVELS[level];
268 return restoreLogLevel;
269 }
270 }
271
272 const DEBUG_PREFIX = ["DEBUG", getColorHex("purple")];
273 const DEFAULT_PREFIX = ["HOOT", getColorHex("primary")];
274 const ERROR_PREFIX = ["ERROR", getColorHex("rose")];
275 const WARNING_PREFIX = ["WARNING", getColorHex("amber")];
276 let nextNetworkLogId = 1;
277
278 //-----------------------------------------------------------------------------
279 // Exports
280 //-----------------------------------------------------------------------------
281
282 /**
283 * @param {string} prefix
284 * @param {string} title
285 */
286 export function makeNetworkLogger(prefix, title) {
287 const id = nextNetworkLogId++;
288 const slicedTitle =
289 title.length > 128 ? title.slice(0, 128) + " (click to show full input)" : title;
290 return {
291 /**
292 * Request logger: blue lotus.
293 * @param {() => any[]} getData
294 */
295 logRequest(getData) {
296 if (!logger.canLog("debug")) {
297 return;
298 }
299 const color = `color: #6960ec`;
300 const args = [`${color}; font-weight: bold;`, color];
301 const [dataHeader, ...otherData] = getData();
302 if (!isNil(dataHeader)) {
303 args.push(dataHeader);
304 }
305 $groupCollapsed(`-> %c${prefix}#${id}%c ${slicedTitle}`, ...args);
306 if (slicedTitle !== title) {
307 $log(title);
308 }
309 for (const data of otherData) {
310 $log(data);
311 }
312 $trace("Request trace:");
313 $groupEnd();
314 },
315 /**
316 * Response logger: dark orange.
317 * @param {() => any[]} getData
318 */
319 logResponse(getData) {
320 if (!logger.canLog("debug")) {
321 return;
322 }
323 const color = `color: #ff8c00`;
324 const args = [`${color}; font-weight: bold;`, color];
325 const [dataHeader, ...otherData] = getData();
326 if (!isNil(dataHeader)) {
327 args.push(dataHeader);
328 }
329 $groupCollapsed(`<- %c${prefix}#${id}%c ${slicedTitle}`, ...args);
330 if (slicedTitle !== title) {
331 $log(title);
332 }
333 for (const data of otherData) {
334 $log(data);
335 }
336 $trace("Response trace:");
337 $groupEnd();
338 },
339 };
340 }
341
342 export const ISSUE_LEVELS = {
343 /**
344 * Suppressed:
345 *
346 * Condition:
347 * - typically: in "todo" tests where issues should be ignored
348 *
349 * Effect:
350 * - all errors and warnings are replaced by 'trace' calls
351 */
352 suppressed: 0,
353 /**
354 * Trace:
355 *
356 * Condition:
357 * - default level within a test run
358 *
359 * Effect:
360 * - warnings are left as-is;
361 * - errors are replaced by 'trace' calls, so that the actual console error
362 * comes from the test runner with a summary of all failed reasons.
363 */
364 trace: 1,
365 /**
366 * Global:
367 *
368 * Condition:
369 * - errors which should be reported globally but not interrupt the run
370 *
371 * Effect:
372 * - warnings are left as-is;
373 * - errors are wrapped with a "HOOT" prefix, as to not stop the current test
374 * run. Can typically be used to log test failed reasons.
375 */
376 global: 2,
377 /**
378 * Critical:
379 *
380 * Condition:
381 * - any error compromising the whole test run and should cancel or interrupt it
382 * - default level outside of a test run (import errors, module root errors, etc.)
383 *
384 * Effect:
385 * - warnings are left as-is;
386 * - errors are left as-is, as to tell the server test to stop the current
387 * (Python) test.
388 */
389 critical: 3,
390 };
391 export const LOG_LEVELS = {
392 runner: 0,
393 suites: 1,
394 tests: 2,
395 debug: 3,
396 };
397
398 export const logger = new Logger(
399 urlParams.loglevel ?? LOG_LEVELS.runner,
400 ISSUE_LEVELS.critical // by default, all errors are "critical", i.e. should abort the whole run
401 );