npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@zyronvexley/log4j2-js

v1.1.0

Published

Log4j2 inspired flexible, configurable logging framework for React, Angular & Node.js

Readme

🪵 log4j2-js

An enterprise-grade, high-performance, and fully configurable Log4j2-inspired logging framework built for TypeScript, React, Angular, and Node.js applications.

npm version license


🚀 What's New in v1.1.0 (Enterprise Features)

  • Zero UI Blocking: WebWorkerAppender offloads heavy log formatting to a background thread.
  • Offline-First Sync: HttpAppender now uses Exponential Backoff and queues logs when offline. Tab-close safety via sendBeacon.
  • Crash Recovery: IndexedDbAppender safely stores logs locally to survive browser crashes.
  • Data Masking: Built-in sanitizer automatically masks PII (Credit Cards, Passwords, Emails).
  • DDoS/Loop Protection: BurstFilter acts as a rate limiter to prevent infinite log loops from crashing your app.
  • Native React Hook: Comes with a built-in useLogger() hook out of the box!

⚠️ Note: the features above ship in v1.1.0. If you're installing today, check the version badge above to confirm what's actually published before relying on them.


⚡ Core Features

  • JSON Configuration Engine — Zero-code logger changes. Switch appenders or log levels dynamically without touching business logic using the ConfigParser.
  • Logger Hierarchy & Additivity — Supports parent-child category log inheritance and additivity rules, just like Java's Log4j2.
  • Multiple Built-in Appenders:
    • 🖥️ ConsoleAppender — Colored terminal/browser logs.
    • 📡 HttpAppender — Asynchronous HTTP batch logging with network awareness.
    • 🗄️ IndexedDbAppender — Persistent browser storage.
    • 🧵 WebWorkerAppender — Multi-threaded background logging.
    • 💾 InMemoryRollingAppender — In-memory log buffer with auto-download and threshold warnings.
    • 🔌 WebSocketAppender & 📬 MqAppender — Real-time log streaming.
  • Flexible Layouts — PatternLayout and JsonLayout with optional metadata and User-Agent toggles.
  • Source Location Parser — Automatically tracks caller file name and line number in dev environments.

📦 Installation

npm install @zyronvexley/log4j2-js

or using Yarn / pnpm:

yarn add @zyronvexley/log4j2-js
# or
pnpm add @zyronvexley/log4j2-js

🚀 Quick Start

1. Initialize Configuration

Call LoggerConfigurator.configure() once during application startup (e.g., in main.ts, index.tsx, or App.tsx):

import { LoggerConfigurator } from "@zyronvexley/log4j2-js";

LoggerConfigurator.configure({
  rootLogger: {
    level: "DEBUG",
    appenders: ["ConsoleLog", "MemoryLog", "ServerHttp"],
  },
  appenders: [
    {
      type: "Console",
      name: "ConsoleLog",
      useColors: true,
      layout: { type: "pattern" },
    },
    {
      type: "InMemoryRolling",
      name: "MemoryLog",
      maxSizeBytes: 5 * 1024 * 1024, // 5 MB Limit
      thresholdPercentage: 80,
    },
    {
      type: "Http",
      name: "ServerHttp",
      endpoint: "https://api.yourdomain.com/logs",
      batchSize: 10,
      layout: { type: "json", includeUserAgent: false },
    },
  ],
  onMemoryThresholdWarning: (currentBytes, maxBytes) => {
    console.warn(
      `⚠️ Log memory reaching limit: ${currentBytes}/${maxBytes} bytes used!`,
    );
  },
});

2. Log Messages Anywhere in Your Code

import { LogManager } from "@zyronvexley/log4j2-js";

const logger = LogManager.getLogger("PaymentService");

logger.debug("Initializing payment flow...");
logger.info("User initiated checkout", { cartId: "CRT-8841", amount: 1200 });

try {
  // Business Logic
} catch (error) {
  logger.error("Payment processing failed", { error });
}

🛠️ Framework Integration Examples

React Integration

Create a simple custom hook, useLogger:

// src/hooks/useLogger.ts
import { useMemo } from "react";
import { LogManager } from "@zyronvexley/log4j2-js";

export function useLogger(categoryName: string) {
  return useMemo(() => LogManager.getLogger(categoryName), [categoryName]);
}
// Usage in Component
import React from "react";
import { useLogger } from "../hooks/useLogger";

export const CheckoutButton = () => {
  const logger = useLogger("CheckoutComponent");

  const handleClick = () => {
    logger.info("Checkout button clicked");
  };

  return <button onClick={handleClick}>Checkout</button>;
};

Angular Integration

Use a standard dependency injection token:

// src/app/logger.provider.ts
import { InjectionToken, Provider } from "@angular/core";
import { LogManager, Logger } from "@zyronvexley/log4j2-js";

export const LOGGER_TOKEN = new InjectionToken<Logger>("APP_LOGGER");

export function provideLogger(category = "Application"): Provider {
  return {
    provide: LOGGER_TOKEN,
    useFactory: () => LogManager.getLogger(category),
  };
}
// Usage in Service/Component
import { Component, Inject } from "@angular/core";
import { LOGGER_TOKEN } from "./logger.provider";
import { Logger } from "@zyronvexley/log4j2-js";

@Component({ selector: "app-user" })
export class UserComponent {
  constructor(@Inject(LOGGER_TOKEN) private logger: Logger) {}

  saveUser() {
    this.logger.info("User saved successfully");
  }
}

⚙️ Configuration Schema

You can also store configuration in an external JSON file (e.g. public/assets/log-config.json):

{
  "rootLogger": {
    "level": "INFO",
    "appenders": ["ConsoleLog", "MemoryLog"]
  },
  "appenders": [
    {
      "type": "Console",
      "name": "ConsoleLog",
      "useColors": true
    },
    {
      "type": "InMemoryRolling",
      "name": "MemoryLog",
      "maxSizeBytes": 10485760,
      "thresholdPercentage": 85
    },
    {
      "type": "WebSocket",
      "name": "RealtimeWs",
      "url": "wss://sockets.example.com/logs"
    }
  ]
}

Load it dynamically:

fetch("/assets/log-config.json")
  .then((res) => res.json())
  .then((config) => LoggerConfigurator.configure(config));

💾 InMemoryRollingAppender Actions

Easily export or flush captured in-memory logs in production for troubleshooting:

import {
  LoggerConfigurator,
  InMemoryRollingAppender,
} from "@zyronvexley/log4j2-js";

const memoryAppender =
  LoggerConfigurator.getAppender<InMemoryRollingAppender>("MemoryLog");

// Get current stats
console.log(memoryAppender?.getStats());

// Download log file directly in browser (.txt) and reset memory
memoryAppender?.downloadAndReset();

🧪 Testing

This project is fully unit-tested using Vitest. To run tests locally:

npm run test

📄 License

This project is licensed under the MIT License.