Skip to content

xnodeoncode/i45-jslogger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NodeJS package

A browser based logger to track events during development and testing. Log entries are written to the console as well as stored in localStorage.

Contents

Properties

i45-jslogger exposes the following properties:

  • loggingEnabled:boolean
    • Enables/disables logging.
  • suppressNative:boolean
    • Enables/disables native logging, client messages and dispatch events are not affected.
  • suppressConsole:boolean
    • Enables/disables console messages.

Methods

i45-jslogger exposes the following methods:

Supported Logging Levels

  • log():

    @param: Message(type:string)

    @param: ...args(type:any)

    @returns: this

    • Executes the log method for all registered clients.
  • info():

    @param: Message(type:string)

    @param: ...args(type:any)

    @returns: this

    • Executes the info method for all registered clients.
  • warn():

    @param: Message(type:string)

    @param: ...args(type:any)

    @returns: this

    • Executes the warn method for all registered clients.
  • error():

    @param: Message(type:string)

    @param: ...args(type:any)

    @returns: this

    • Executes the error message for all registered clients.
  • isValidClient():

    @param: custom logger(type:object)

    @returns: boolean

    • Validates that a client has the required methods.
  • addClient():

    @param: custom logger(type:object) @returns: this

    • Validates that a client has the required methods and adds it call tree.
  • removeClient():

    @param: name(type:string)

    @returns: this

    • Removes a client by name.
  • clients():

    @returns: Array

    • Returns an array of all registered clients.
  • removeAllClients():

    @returns: this

    • Clears all registered clients.
  • addEvent():this

    • Adds an event to the event log without logging.
  • getEvents():

    @returns: Array

    • Returns an array of all events captured in the event log.
  • clearEvents():

    @returns: _this

    • Removes all events from local storage and the console.

Installation

npm i i45-jslogger

Usage

import { Logger } from "i45-jslogger";

var logger = new Logger();

logger.info("This is an info message.");
logger.warn("This is a warn message.");
logger.error("This is an error message.");

Console output: Console output

Local storage output: Local storage

Logging Levels

Filter by logging levels in the Console.

Console set to display warning and errors only. Logging levels

Class/Module Usage

import { Logger } from "i45-jslogger";

export class MyClass {
  // private field for logging.
  #loggingEnabled;
  #logger;

  constructor() {
    this.#loggingEnabled = false;
    this.#logger = new Logger();
  }

  enableLogging(value = false) {
    if (typeof value !== "boolean") {
      // if logging is enabled, the error will be logged and also thrown to stop further processing.
      // the second parameter, throwError, determines if the error is thrown or not.
      this.#error(`The method enableLogging() expected a boolean, but got ${typeof value}`, true);
    }
    this.#loggingEnabled = value;
  }

  doSomething(){

    //... method code

    // log the action.
    this.#info("We've just done something".);
  }

  #info(message, ...args){
    if(this.#loggingEnabled){
      this.#logger.info(messge, ...args);
    }
  }

  #warn(message, ...args){
    if(this.#loggingEnabled){
      this.#logger.warn(message, ...args);
    }
  }

  #error(message, throwError = false, ...args){
    if(this.#loggingEnabled){
      this.#logger.error(message, ...args);
    }

    // Even when logging is disabled, an error can be thrown when necessary.
    if(throwError){
      throw new Error(message, ...args);
    }
  }
}

var myClass = new MyClass();
myClass.enableLogging(true);
myClass.doSomething();
// console output
[INFO] 2025-08-26T14:41:25.073z: We've just done something.

Using a Custom Logger (Client)

i45-jslogger accepts additional clients, such as a file system logger, as long as the required methods are implemented.

Required methods:

  • log()
  • info()
  • warn()
  • error()

Add a new logger with:

import { Logger } from "i45-jslogger";

var logger = new Logger();
logger.addClient(myCustomLogger);

Each method call on i45-jslogger will result in the corresponding method on clients. Client calls are synchronous and in the order that the clients were added. See the sample code below.

Complete Example

import { Logger } from "i45-jslogger";

export class MyClass {
  // private field for logging.
  #loggingEnabled;
  #logger;

  constructor() {
    this.#logger = new Logger();

    // logging can be enabled/disabled either in the consuming class, or on the logger itself.
    // For example: this.#logger.loggingEnabled = true|false;
    this.#loggingEnabled = true;
  }

  enableLogging(value = false) {
    if (typeof value !== "boolean") {
      // if logging is enabled, the error will be logged and optionally thrown to stop further execution.

      // the second parameter, throwError, is optional, but can be used to throw the error if logging is disabled.
      this.#error(`The method enableLogging() expected a boolean, but got ${typeof value}`, throwError=true);
    }
    this.#loggingEnabled = value;
    return this;
  }

  doSomething(){

    try {
        // log the action.
        this.#info("Working on something".);

        //... method code

    } catch (e){

        // log and/or throw the error. [See method below.]
        this.#error("An error occurred.",throwError = true, e);

    } finally {

        this.#info("Something is done.");
    }
    return this;
  }

  useCustomLogger(myCustomLogger){
    // add new client
    // multiple clients can be added.
    // Client calls are synchronous and occur in the order that clients are added.
    // Logger.info() calls -> customLogger1.info(), customLogger2.info(), ...etc.
      this.#logger.addClient(myCustomLogger);

      return this;
  }

  #info(message, ...args){
    if(this.#loggingEnabled){
      this.#logger.info(messge, ...args);
    }
    return this;
  }

  #warn(message, ...args){
    if(this.#loggingEnabled){
      this.#logger.warn(message, ...args);
    }
    return this;
  }

  #error(message, throwError = false, ...args){
    if(this.#loggingEnabled){
      this.#logger.error(message, ...args);
    }

    // An error can still be thrown with logging disabled.
    if(throwError){
      throw new Error(message, ...args);
    }
    return this;
  }
}

var myClass = new MyClass();
myClass.useCustomLogger(myCustomLogger).enableLogging(true);
myClass.doSomething();

Event Listeners

i45-jslogger dispatches custom events on the window object. An EventListener can be used to subscribe to the events.

The following dispatch events are (case-sensitive):

  • "LOG"
  • "INFO"
  • "WARN"
  • "ERROR"

To capture the event, add an event listener as below.

window.addEventListener("LOG", (event) => {
  console.log("Custom event received:", event.detail);
});

window.addEventListener("INFO", (event) => {
  console.log("Custom event received:", event.detail);
});

window.addEventListener("WARN", (event) => {
  console.log("Custom event received:", event.detail);
});

window.addEventListener("ERROR", (event) => {
  console.log("Custom event received:", event.detail);
});

Disable Events

Window events are enabled by default, and can be disabled using:

import { Logger } from "i45-jslogger";

const logger = new Logger();

//disable window events
logger.dispatchEvents = false;

About

A simple JavaScript logger for capturing events in the console and local storage.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published