1.0.5 • Published 6 months ago

@js-utility/logger v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

Logger Utility for Javascript / Typescript

A flexible and powerful logging utility for Node.js projects, built with modern JavaScript and TypeScript in mind.
Logger provides advanced features like log levels, file and console output, log rotation, colorized logs, trace IDs, and full TypeScript support—making it ideal for scalable applications and robust debugging.

If this package has been helpful to you, your support goes a long way in helping maintain it, improve its features, and build more open-source tools like it. Buy Me a Coffee ☕

Features

  • Log Levels: ERROR, WARN, INFO, DEBUG
  • Console and File Logging: Output logs to console, file, or both
  • Log Rotation & Compression: Rotate log files by date and size, compress old logs automatically
  • Colorized Output: Colorful console logs for better readability (using chalk)
  • Trace IDs & Metadata: Attach trace IDs and extra metadata to logs
  • Global Logger Support: Set and use a global logger instance
  • Customizable: Configure log file path, log level, silence mode, and more
  • TypeScript Support: Fully typed API

Installation

npm install @js-utility/logger

Usage

Basic Example

import { Logger, createLogger, LogLevel } from '@js-utility/logger';

const logger = createLogger('my-service', {
  level: LogLevel.INFO,
  logToFile: true,
  logFilePath: 'logs/my-service.log',
  maxSizeMB: 10,
  color: true,
});

logger.info('Service started');
logger.warn('Low disk space', { disk: '95%' });
logger.error(new Error('Something went wrong'));
logger.debug('Debug details', { foo: 'bar' });

Global Logger

import { Logger } from '@js-utility/logger';

Logger.setGlobalConfig({
  name: 'GLOBAL',
  level: LogLevel.WARN,
  logToFile: true,
});

const globalLogger = Logger.getGlobalLogger();
globalLogger.info('This will not be shown (level is WARN)');
globalLogger.error('This is an error');

Attaching Trace IDs and Metadata

const logger = createLogger('api', { traceId: 'req-123' });
logger.info('Request received', { userId: 42 });
logger.setTraceId('req-456');
logger.setExtra({ session: 'abc' });
logger.info('Another request');

Muting the Logger

logger.setSilent(true); // Mute all logs
logger.setSilent(false); // Unmute

API

LoggerOptions

OptionTypeDefaultDescription
namestring'GLOBAL'Logger name
levelLogLevelINFOMinimum log level
logToFilebooleanfalseEnable file logging
logFilePathstring'application.log'Log file path
traceIdstringundefinedOptional trace ID
colorbooleantrueColorize console output
maxSizeMBnumberundefinedMax log file size before rotation (MB)
silentbooleanfalseSilence all logs
globalbooleanfalseMake this the global logger
extraRecord<string,any>undefinedExtra metadata for every log

Logger Methods

  • error(...args: any[]) — Log an error message or Error object
  • warn(...args: any[]) — Log a warning message
  • info(...args: any[]) — Log an info message
  • debug(...args: any[]) — Log a debug message
  • setTraceId(traceId?: string) — Set the trace ID for this logger instance
  • setExtra(extra?: object) — Set extra metadata for this logger instance
  • setSilent(silent = true) — Mute or unmute this logger instance

Factory

  • createLogger(name: string, options?: Omit<LoggerOptions, 'name'>): Logger

Global Logger

  • Logger.setGlobalConfig(config: Partial<LoggerOptions>)
  • Logger.getGlobalLogger(): Logger

Log Rotation & Compression

  • Log files are rotated daily and/or when exceeding maxSizeMB.
  • Old log files are compressed to .gz automatically.

Example Log Output

[2025-04-27T12:34:56.789Z] [INFO] [my-service] {"userId":42} Service started
[2025-04-27T12:35:00.123Z] [ERROR] [my-service] [trace:req-123] {"foo":"bar"} Something went wrong

📘 TypeScript Support

This package is built with full TypeScript support. All functions are type-safe, and type definitions are bundled, so you get autocomplete, inline documentation, and compile-time safety out of the box, no need to install @types.


🧪 Testing

This package is thoroughly tested using Jest, with a focus on correctness, edge cases, and null-safety.


🤝 Contributing

This project is maintained privately. While direct contributions (e.g., pull requests or code changes) are not open to the public, feedback, suggestions, and issue reports are always welcome.

If you notice any bugs, edge cases, or have ideas for improvement, feel free to reach out or open an issue (if access is available). Your input helps make the package more robust and useful for everyone!


💖 Support / Donate

If you find this package useful, consider supporting its development. Your support helps maintain the project, improve documentation, and add new features.

Support as through :


💬 Support & Feedback

Have ideas, suggestions, or found a bug? I'd love to hear from you!

  • Feedback: Whether it’s a feature request or an edge case you'd like handled, your input helps improve the package.
  • Issues: If you run into a bug or unexpected behavior, feel free to open an issue (if the repo is accessible).
  • Reach Out: You can also reach out directly for feedback or discussion via email or the contact details in the repository.

Your feedback helps shape better tools for everyone using this package.