Skip to content

A simple, asynchronous file logger for JavaScript and TypeScript, compatible with both Node.js and Bun.

License

Notifications You must be signed in to change notification settings

enix1032/logger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@en32/logger

A simple, asynchronous file logger for JavaScript and TypeScript, compatible with both Node.js and Bun.

2025-09-06T00:52:08.909Z [INFO ]: Application is running...
2025-09-06T00:52:08.923Z [DEBUG]: This is a debug message.
2025-09-06T00:52:08.924Z [INFO ]: {"user":"John Doe","action":"login","status":"success"}
2025-09-06T00:52:08.927Z [ERROR]: Error: Error - Database connection failed! | Stack: Error: Database connection failed! at <anonymous> (/@en32/logger/examples/index.js:23:15)
2025-09-06T00:52:08.927Z [WARN ]: A warning message... [@ <anonymous> (/src/index.ts:257)]
2025-09-06T00:52:08.928Z [INFO ]: Log level changed to INFO.
[
  {
    "timestamp": "2025-09-06T00:52:08.923Z",
    "level": "DEBUG",
    "message": "This is a debug message."
  },
  {
    "timestamp": "2025-09-06T00:52:08.924Z",
    "level": "INFO",
    "message": "{\"user\":\"John Doe\",\"action\":\"login\",\"status\":\"success\"}"
  },
  {
    "timestamp": "2025-09-06T00:52:08.927Z",
    "level": "ERROR",
    "message": "Error: Error - Database connection failed! | Stack: Error: Database connection failed! at <anonymous> (/@en32/logger/examples/index.js:23:15)"
  },
  {
    "timestamp": "2025-09-06T00:52:08.927Z",
    "level": "WARN",
    "message": "A warning message...",
    "location": {
      "at": "<anonymous>",
      "path": "/src/index.ts",
      "line": 257
    }
  },
  {
    "timestamp": "2025-09-06T00:52:08.928Z",
    "level": "INFO",
    "message": "Log level changed to INFO."
  }
]

This package provides a basic Logger class that writes timestamped and leveled log messages to a file. It is designed to be straightforward and easy to use for simple logging needs in server-side applications.

Features

  • Asynchronous File Writing: All log writing operations are non-blocking.
  • Log Levels: Supports DEBUG, INFO, WARN, and ERROR levels to control log verbosity.
  • Customizable Log Level: Change the logging level at runtime.
  • Error Handling: Automatically formats Error objects, including their stack traces.
  • Object Truncation: Truncates large object messages to prevent log files from growing excessively.
  • JSON Log Reading: Read and parse log entries from the file into a JSON format for easy analysis.
  • Bun & Node.js Compatible: Built with modern JavaScript/TypeScript and file system APIs that work seamlessly in both runtimes.

Installation

npm install @en32/logger
# or
bun add @en32/logger
# or
yarn add @en32/logger

Usage

Basic Example

Here's a simple example of how to use the logger.

import Logger, { LogLevel } from '@en32/logger';

// Create a logger instance. The log file will be located at './logs/app.log'.
// Set the log level to DEBUG and enable logging.
const logger = new Logger('./logs/app.log', LogLevel.DEBUG, true);

(async () => {
  // Log an informational message
  await logger.info('Application is starting up...');

  // Log a debug message
  // This will only be written to the file if the log level is DEBUG or lower.
  await logger.debug('This is a debug message.');

  // Log a warning with an object
  await logger.warn({
    component: 'Database',
    message: 'Connection pool is running low.'
  });

  // Log an error with an Error object
  try {
    throw new Error('Failed to connect to the database!');
  } catch (error) {
    await logger.error(error);
  }

  // Reading the last 5 logs from the file as a JSON array
  console.log('Reading the last 5 logs...');
  const recentLogs = await logger.readLogsAsJson({ limit: 5 });
  if (recentLogs) {
    console.log(JSON.stringify(recentLogs, null, 2));
  }

})();

Constructor

The Logger constructor takes four optional arguments:

new Logger(
  filePath: string,
  level?: LogLevel,
  allowed?: boolean,
  truncateLimit?: number
);
  • filePath: The path to the log file. The directory will be created if it doesn't exist.
  • level: The minimum log level to write. Messages with a lower level will be ignored. Defaults to LogLevel.INFO.
  • allowed: A boolean to enable or disable logging. If false, no logs will be written. Defaults to false.
  • truncateLimit: The maximum length of a stringified object message. Messages longer than this will be truncated. Defaults to 2000.

Log Levels

The LogLevel enum provides four levels of severity:

  • LogLevel.DEBUG (0)
  • LogLevel.INFO (1)
  • LogLevel.WARN (2)
  • LogLevel.ERROR (3)

Methods

  • logger.setLevel(level: LogLevel): void Dynamically changes the minimum log level.

  • logger.debug(message: string | object, location?: LogLocation): Promise<void> Writes a debug message.

  • logger.info(message: string | object, location?: LogLocation): Promise<void> Writes an informational message.

  • logger.warn(message: string | object | Error, location?: LogLocation): Promise<void> Writes a warning message. Can accept an Error object.

  • logger.error(message: string | object | Error, location?: LogLocation): Promise<void> Writes an error message. Can accept an Error object.

  • logger.readLogsAsJson(options?: ReadLogsOptions): Promise<ReadLogsResult | null> Reads log entries from the file and parses them into a JSON format.

    ReadLogsOptions:

    • limit?: number: The number of recent log lines to read. Defaults to 100.
    • as?: 'object' | 'array': The format of the returned logs. object returns an array of objects, while array returns a nested array [timestamp, level, message, location]. Defaults to object.
    • filter?: string | string[]: Filters logs by a specific level (e.g., 'ERROR' or 'INFO|WARN').
    • parseJsonMessage?: boolean: Whether to attempt parsing the log message as a JSON object. Defaults to true.

License

This package is distributed under the MIT License.

About

A simple, asynchronous file logger for JavaScript and TypeScript, compatible with both Node.js and Bun.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published