]> Git Repo - pico-vscode.git/blob - src/logger.mts
Fix linting errors
[pico-vscode.git] / src / logger.mts
1 /* eslint-disable @typescript-eslint/no-unused-vars */
2 type LogLevel = "debug" | "info" | "warn" | "error";
3
4 const logLevel: LogLevel = process.env.BUILD ? "warn" : "debug";
5
6 // ANSI escape codes for colored console output
7 const red = "\x1b[31m";
8 const green = "\x1b[32m";
9 const yellow = "\x1b[33m";
10 const blue = "\x1b[34m";
11 const magenta = "\x1b[35m";
12 // ANSI escape code to reset color
13 const reset = "\x1b[0m";
14
15 /**
16  * Interface for objects that can be converted to a string with the toString() method.
17  */
18 interface Stringable {
19   toString(): string;
20 }
21
22 /**
23  * Logger class to log messages to the console with different log levels and identifiable source.
24  */
25 export default class Logger {
26   private className: string;
27
28   /**
29    * Creates a new Logger instance.
30    *
31    * @param className The name of the class the logger is used in.
32    */
33   constructor(className: string) {
34     this.className = className;
35   }
36
37   /**
38    * Logs the given message to the console.
39    *
40    * @param message The message to log.
41    * @param optionalParams Optional parameters to log.
42    */
43   public static log(
44     message: string | undefined,
45     ...optionalParams: Stringable[]
46   ): void {
47     console.log(`[raspberry-pi-pico] ${message}`, ...optionalParams);
48   }
49
50   private shouldLog(level: LogLevel): boolean {
51     const levels: LogLevel[] = ["debug", "info", "warn", "error"];
52
53     return levels.indexOf(level) >= levels.indexOf(logLevel);
54   }
55
56   public info(message: string, ...optionalParams: Stringable[]): void {
57     if (this.shouldLog("info")) {
58       console.info(`[INFO] [${this.className}] ${message}`, ...optionalParams);
59     }
60   }
61
62   public warn(message: string, ...optionalParams: Stringable[]): void {
63     if (this.shouldLog("warn")) {
64       console.warn(
65         `[${yellow}WARN${reset}] [${this.className}] ${message}`,
66         ...optionalParams
67       );
68     }
69   }
70
71   public error(message: string | Error, ...optionalParams: Stringable[]): void {
72     if (this.shouldLog("error")) {
73       if (message instanceof Error) {
74         message = message.message;
75       }
76
77       console.error(
78         `[${red}ERROR${reset}] [${this.className}] ${message}`,
79         ...optionalParams
80       );
81     }
82   }
83
84   public debug(message: string, ...optionalParams: Stringable[]): void {
85     if (this.shouldLog("debug")) {
86       console.debug(
87         `[DEBUG] [${this.className}] ${message}`,
88         ...optionalParams
89       );
90     }
91   }
92 }
This page took 0.035453 seconds and 4 git commands to generate.