microsoft/qdk

Public

mirrored from https://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
c8adde746a7aaa0185fd4eac69af19d259ce1faa

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

npm/src/log.ts

75lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4// Logging infrastructure for JavaScript environments (e.g. browser and node.js)
5//
6// Ideally this should be the only module to have global side effects and run code
7// on module load (i.e. other modules should consist almost entirely of declarations
8// and exports at the top level), which means it is configurable and usable from
9// the host environment after import resolution and before other logic runs.
10
11declare global {
12 // Align with VS Code names (but not level numbers)
13 // 0 = off
14 // 1 = error
15 // 2 = warn
16 // 3 = info
17 // 4 = debug (called 'verbose' in VS Code)
18 // 5 = trace
19 // Note this also aligns with the Rust log crate macros/levels
20 // See https://docs.rs/log/latest/log/
21 var qscLogLevel: number; // eslint-disable-line no-var
22 var qscLog: typeof log; // eslint-disable-line no-var
23}
24
25type LogLevel = "off" | "error" | "warn" | "info" | "debug" | "trace";
26
27export const log = {
28 setLogLevel(level: LogLevel | number) {
29 if (typeof level === "string") {
30 // Convert to number
31 const lowerLevel = level.toLowerCase();
32 const levels = ["off", "error", "warn", "info", "debug", "trace"];
33 let newLevel = 0;
34 levels.forEach((name, idx) => {
35 if (name === lowerLevel) newLevel = idx;
36 });
37 globalThis.qscLogLevel = newLevel;
38 } else {
39 globalThis.qscLogLevel = level;
40 }
41 },
42 getLogLevel(): number {
43 return globalThis.qscLogLevel || 0;
44 },
45 /* eslint-disable @typescript-eslint/no-explicit-any */
46 error(...args: any) {
47 if (qscLogLevel >= 1) console.error(...args);
48 },
49 warn(...args: any) {
50 if (qscLogLevel >= 2) console.warn(...args);
51 },
52 info(...args: any) {
53 if (qscLogLevel >= 3) console.info(...args);
54 },
55 debug(...args: any) {
56 if (qscLogLevel >= 4) console.debug(...args);
57 },
58 trace(...args: any) {
59 // console.trace in JavaScript just writes a stack trace at info level, so use 'debug'
60 if (qscLogLevel >= 5) console.debug(...args);
61 },
62 /* eslint-enable @typescript-eslint/no-explicit-any */
63 never(val: never) {
64 // Utility function to ensure exhaustive type checking. See https://stackoverflow.com/a/39419171
65 log.error("Exhaustive type checking didn't account for: %o", val);
66 },
67};
68
69// Default to the 'error' level for logging
70if (typeof globalThis.qscLogLevel === "undefined") {
71 log.setLogLevel("error");
72}
73
74// Enable globally for easy interaction and debugging in live environments
75globalThis.qscLog = log;