ts-class-logger
v2.0.1
Published
Simple, modern logger for TypeScript classes with formatting and colors.
Maintainers
Readme
TSClassLogger
Simple, modern logger for TypeScript classes with formatting and colors.
Installation
npm install ts-class-loggerQuick Start
import { Logger } from "ts-class-logger";
const logger = new Logger("MyClass");
logger.debug("Debug message");
logger.info("Info message", { data: 123 });
logger.warn("Warning!");
logger.error("Error", new Error("something failed"));Features
- No double-invoke - Just
logger.debug("msg"), notlogger.debug("msg")() - Log levels - TRACE, DEBUG, INFO, LOG, WARN, ERROR, OFF
- Formatted output - Customizable format strings with timestamps
- Colors - ANSI colors in Node.js, CSS styling in browsers
- Callbacks - Hook into log events for external services
- Environment detection - Auto-detects Node.js vs browser
Configuration
import { Logger, Level, LoggerOptions } from "ts-class-logger";
const options: LoggerOptions = {
level: Level.DEBUG, // Minimum level to log
format: "[{timestamp}] {level} [{name}]: {message}",
timestampFormat: "ISO", // "ISO" | "locale" | custom function
colors: "auto", // true | false | "auto"
logToConsole: true, // Set false to only use callbacks
// Callbacks
onDebug: (args) => { /* ... */ },
onAny: (level, args) => { /* send to logging service */ },
};
const logger = new Logger("MyClass", options);Using with Classes
Use this.constructor.name for automatic class name detection:
class MyService {
private logger = new Logger(this.constructor.name);
doWork() {
this.logger.info("Processing...");
// Output: [2024-01-15T10:30:00Z] INFO [MyService]: Processing...
}
}Format Tokens
{timestamp}- Formatted timestamp{level}- Log level (DEBUG, INFO, etc.){name}- Logger name{message}- Log arguments
Log Levels
From lowest to highest priority:
Level.TRACE- Verbose debuggingLevel.DEBUG- Debug informationLevel.INFO- General informationLevel.LOG- Standard logsLevel.WARN- WarningsLevel.ERROR- ErrorsLevel.OFF- Disable all logging
Migration from v1
Breaking changes in v2:
| v1 | v2 |
|----|-----|
| logger.debug("msg")() | logger.debug("msg") |
| options.debug callback | options.onDebug |
| forceConsoleLog option | Removed |
License
ISC
