@ecopages/logger
Advanced tools
+5
-0
@@ -43,2 +43,6 @@ declare const Level: { | ||
| colors?: Partial<ColorConfig>; | ||
| /** | ||
| * If true, logs when timers start. Useful for debugging. | ||
| */ | ||
| verboseTimer?: boolean; | ||
| } | ||
@@ -52,2 +56,3 @@ /** | ||
| private options; | ||
| private readonly timers; | ||
| /** | ||
@@ -54,0 +59,0 @@ * Creates a new instance of the Logger class. |
+1
-1
@@ -1,1 +0,1 @@ | ||
| var q={INFO:"INFO",ERROR:"ERROR",WARN:"WARN",DEBUG:"DEBUG",TIMER:"TIMER"},V={level:q.INFO},X={level:q.ERROR},Y={level:q.WARN},Z={level:q.DEBUG},H=typeof window!=="undefined",_={INFO:"color: #00ff00",ERROR:"color: #ff0000",WARN:"color: #ffff00",DEBUG:"color: #00ffff",TIMER:"color: #ff00ff"},$={INFO:"\x1B[32m",ERROR:"\x1B[31m",WARN:"\x1B[33m",DEBUG:"\x1B[36m",TIMER:"\x1B[35m"};class y{prefix;colors;options={debug:!1,color:!0,timestampFormat:"time"};constructor(j,k){if(this.prefix=j,k)this.options={...this.options,...k};this.colors={...H?_:$,...k?.colors}}info(...j){return this.logInternal(V,...j),this}warn(...j){return this.logInternal(Y,...j),this}error(...j){return this.logInternal(X,...j),this}debug(...j){if(this.options.debug)this.logInternal(Z,...j);return this}time(j,k=q.TIMER){if(!this.options.color){console.time(j);return}if(H){console.time(`%c${j}`),console.log(`%c${j}`,this.getColor(k));return}let z=this.getColor(k);console.time(`${z}${j}\x1B[0m`)}timeEnd(j,k=q.TIMER){if(!this.options.color){console.timeEnd(j);return}if(H){console.timeEnd(`%c${j}`),console.log(`%c${j}`,this.getColor(k));return}let z=this.getColor(k);console.timeEnd(`${z}${j}\x1B[0m`)}getTimestamp(){if(!this.options.timestamp)return"";let j=new Date,k;switch(this.options.timestampFormat){case"full":k={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1};break;case"short":k={month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1};break;default:k={hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}}return`[${j.toLocaleString("en-US",k)}] `}getColor(j){return this.colors[j]??""}getFormatSpecifier(j){if(j===null)return"%s";if(j===void 0)return"%s";switch(typeof j){case"object":return"%o";case"number":return"%d";case"boolean":return"%s";default:return"%s"}}logInternal(j,...k){let J=this.getTimestamp()+this.prefix;if(!this.options.color){console.log(J,...k);return}if(H){let P=j?this.getColor(j.level):"",Q=k.map((S)=>this.getFormatSpecifier(S));console.log(`%c${J} ${Q.join(" ")}`,P,...k);return}let K=j?this.getColor(j.level):"",M="\x1B[0m";console.log(`${K}${J}`,...k,M)}}export{y as Logger}; | ||
| var z={INFO:"INFO",ERROR:"ERROR",WARN:"WARN",DEBUG:"DEBUG",TIMER:"TIMER"},V={level:z.INFO},X={level:z.ERROR},Y={level:z.WARN},Z={level:z.DEBUG},J=typeof window!=="undefined",_={INFO:"color: #00ff00",ERROR:"color: #ff0000",WARN:"color: #ffff00",DEBUG:"color: #00ffff",TIMER:"color: #ff00ff"},$={INFO:"\x1B[32m",ERROR:"\x1B[31m",WARN:"\x1B[33m",DEBUG:"\x1B[36m",TIMER:"\x1B[35m"};class y{prefix;colors;options={debug:!1,color:!0,timestampFormat:"time",verboseTimer:!1};timers=new Map;constructor(j,k){if(this.prefix=j,k)this.options={...this.options,...k};this.colors={...J?_:$,...k?.colors}}info(...j){return this.logInternal(V,...j),this}warn(...j){return this.logInternal(Y,...j),this}error(...j){return this.logInternal(X,...j),this}debug(...j){if(this.options.debug)this.logInternal(Z,...j);return this}time(j,k=z.TIMER){if(!this.options.color){console.time(`${this.prefix} ${j}`);return}if(this.timers.set(j,performance.now()),this.options.verboseTimer)if(J)console.log(`%c${this.prefix} ${j}: start`,this.getColor(k));else{let H=this.getColor(k);console.log(`${H}${this.prefix} ${j}: start\x1B[0m`)}}timeEnd(j,k=z.TIMER){if(!this.options.color){console.timeEnd(`${this.prefix} ${j}`);return}let H=this.timers.get(j);if(H===void 0){console.warn(`Timer '${this.prefix} ${j}' does not exist`);return}let q=performance.now()-H;if(this.timers.delete(j),J)console.log(`%c${this.prefix} ${j}: ${q.toFixed(2)}ms`,this.getColor(k));else{let K=this.getColor(k);console.log(`${K}${this.prefix} ${j}: ${q.toFixed(2)}ms\x1B[0m`)}}getTimestamp(){if(!this.options.timestamp)return"";let j=new Date,k;switch(this.options.timestampFormat){case"full":k={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1};break;case"short":k={month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1};break;default:k={hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}}return`[${j.toLocaleString("en-US",k)}] `}getColor(j){return this.colors[j]??""}getFormatSpecifier(j){if(j===null)return"%s";if(j===void 0)return"%s";switch(typeof j){case"object":return"%o";case"number":return"%d";case"boolean":return"%s";default:return"%s"}}logInternal(j,...k){let q=this.getTimestamp()+this.prefix;if(!this.options.color){console.log(q,...k);return}if(J){let P=j?this.getColor(j.level):"",Q=k.map((S)=>this.getFormatSpecifier(S));console.log(`%c${q} ${Q.join(" ")}`,P,...k);return}let K=j?this.getColor(j.level):"",M="\x1B[0m";console.log(`${K}${q}`,...k,M)}}export{y as Logger}; |
+1
-1
| { | ||
| "name": "@ecopages/logger", | ||
| "version": "0.2.0", | ||
| "version": "0.2.1", | ||
| "license": "MIT", | ||
@@ -5,0 +5,0 @@ "main": "./dist/logger.js", |
+110
-39
| # @ecopages/logger | ||
| A lightweight, flexible logging library. This logger supports multiple log levels and allows for easy extension and integration into any project. | ||
| A lightweight, flexible logging library with color support, timestamps, and timer functionality. This logger supports multiple log levels and allows for easy extension and integration into any project. | ||
| ## Features | ||
| - **Multiple Log Levels**: Supports `INFO`, `ERROR`, `WARN`, and `DEBUG` log levels for granular control over logging output. | ||
| - **Prefixed Messages**: Allows for prefixing log messages for better identification and filtering. | ||
| - **Easy to Extend**: Designed with simplicity in mind, making it easy to extend or modify to fit specific requirements. | ||
| - **Multiple Log Levels**: Supports `INFO`, `ERROR`, `WARN`, and `DEBUG` log levels | ||
| - **Colored Output**: Configurable colors for different log levels in both browser and Node.js environments | ||
| - **Timestamps**: Optional timestamps with configurable formats | ||
| - **Timer Support**: Built-in timer functionality for performance measurements | ||
| - **Prefixed Messages**: Customizable prefix for all log messages | ||
| - **Environment Detection**: Automatically adapts output format for browser or Node.js environments | ||
| - **Extensible**: Easy to extend with custom functionality | ||
| ## Usage | ||
| ## Installation | ||
| First, import the `Logger` class from the `logger.ts` file: | ||
| ```ts | ||
| import { Logger } from "./path/to/logger"; | ||
| ```bash | ||
| npm install @ecopages/logger | ||
| # or | ||
| yarn add @ecopages/logger | ||
| # or | ||
| bun add @ecopages/logger | ||
| ``` | ||
| Create an instance of the Logger class, optionally specifying a prefix for all log messages: | ||
| ## Basic Usage | ||
| ```ts | ||
| import { Logger } from "@ecopages/logger"; | ||
| // Create a basic logger | ||
| const logger = new Logger("[my-app]"); | ||
| ``` | ||
| Use the logger instance to log messages at different levels: | ||
| ```ts | ||
| // Log messages at different levels | ||
| logger.info("This is an informational message"); | ||
| logger.warn("This is a warning message"); | ||
| logger.error("This is an error message"); | ||
| logger.debug("This is a debug message"); | ||
| logger.debug("This is a debug message"); // Only shown if debug is enabled | ||
| ``` | ||
| ```bash | ||
| [my-app] This is an informational message | ||
| [my-app] This is a warning message | ||
| [my-app] This is an error message | ||
| [my-app] This is a debug message | ||
| ## Advanced Configuration | ||
| The logger supports various configuration options: | ||
| ```ts | ||
| const logger = new Logger("[my-app]", { | ||
| debug: true, // Enable debug messages | ||
| color: true, // Enable colored output | ||
| timestamp: true, // Add timestamps to messages | ||
| timestampFormat: 'full', // Configure timestamp format | ||
| verboseTimer: true, // Show timer start messages | ||
| colors: { // Custom colors | ||
| INFO: 'color: purple', | ||
| ERROR: 'color: darkred' | ||
| } | ||
| }); | ||
| ``` | ||
| ## API | ||
| ### Configuration Options | ||
| ### Constructor | ||
| | Option | Type | Default | Description | | ||
| |--------|------|---------|-------------| | ||
| | `debug` | boolean | `false` | Enable debug level messages | | ||
| | `color` | boolean | `true` | Enable colored output | | ||
| | `timestamp` | boolean | `false` | Add timestamps to messages | | ||
| | `timestampFormat` | 'full' \| 'time' \| 'short' | 'time' | Timestamp format | | ||
| | `verboseTimer` | boolean | `false` | Show timer start messages | | ||
| | `colors` | Partial<ColorConfig> | - | Custom colors for log levels | | ||
| - `Logger(prefix: string)`: Creates a new logger instance with the specified prefix. | ||
| ### Timestamp Formats | ||
| ### Methods | ||
| - `full`: `YYYY-MM-DD HH:mm:ss` | ||
| - `time`: `HH:mm:ss` | ||
| - `short`: `MM-DD HH:mm:ss` | ||
| - `info(...args: any[])`: Logs an informational message. | ||
| - `warn(...args: any[])`: Logs a warning message. | ||
| - `error(...args: any[])`: Logs an error message. | ||
| - `debug(...args: any[])`: Logs a debug message. | ||
| ## Timer Functionality | ||
| ### Extending the Logger | ||
| ```ts | ||
| // Start a timer | ||
| logger.time("operation"); | ||
| To extend the logger with additional functionality, you can subclass the Logger class. For example, to add a method for logging fatal errors: | ||
| // ... some operations ... | ||
| // End the timer and log duration | ||
| logger.timeEnd("operation"); | ||
| ``` | ||
| ## Custom Colors | ||
| Colors can be customized differently for browser and Node.js environments: | ||
| ```ts | ||
| class ExtendedLogger extends Logger { | ||
| fatal(...args: any[]) { | ||
| // Custom implementation for fatal errors | ||
| // Browser colors (CSS syntax) | ||
| const logger = new Logger("[my-app]", { | ||
| colors: { | ||
| INFO: 'color: purple', | ||
| ERROR: 'color: darkred', | ||
| WARN: 'color: orange', | ||
| DEBUG: 'color: cyan', | ||
| TIMER: 'color: magenta' | ||
| } | ||
| } | ||
| }); | ||
| // Node.js colors (ANSI codes) | ||
| const logger = new Logger("[my-app]", { | ||
| colors: { | ||
| INFO: '\x1b[35m', // Purple | ||
| ERROR: '\x1b[31m', // Red | ||
| WARN: '\x1b[33m', // Yellow | ||
| DEBUG: '\x1b[36m', // Cyan | ||
| TIMER: '\x1b[35m' // Magenta | ||
| } | ||
| }); | ||
| ``` | ||
| ### Debugging Instructions | ||
| ## Examples | ||
| By default, the debugging feature is turned off. To enable it you can provide an options object to the logger constructor. | ||
| ### With Timestamps and Colors | ||
| ```ts | ||
| const logger = new Logger("[my-app]", { | ||
| timestamp: true, | ||
| timestampFormat: 'full' | ||
| }); | ||
| logger.info("Application started"); | ||
| // Output: [2024-02-16 15:30:45] [my-app] Application started | ||
| ``` | ||
| ### With Debug Messages | ||
| ```ts | ||
| const logger = new Logger("[my-app]", { debug: true }); | ||
| logger.debug("Configuration loaded:", { port: 3000 }); | ||
| // Output: [my-app] Configuration loaded: { port: 3000 } | ||
| ``` | ||
| ```bash | ||
| [my-app] This is a debug message | ||
| ``` | ||
| ### With Timer | ||
| ```ts | ||
| const logger = new Logger("[my-app]", { verboseTimer: true }); | ||
| logger.time("db-query"); | ||
| // ... database operation ... | ||
| logger.timeEnd("db-query"); | ||
| // Output: [my-app] db-query: 123.45ms | ||
| ``` |
11343
24.51%107
5.94%147
90.91%