@zyronvexley/log4j2-js
v1.1.0
Published
Log4j2 inspired flexible, configurable logging framework for React, Angular & Node.js
Maintainers
Readme
🪵 log4j2-js
An enterprise-grade, high-performance, and fully configurable Log4j2-inspired logging framework built for TypeScript, React, Angular, and Node.js applications.
🚀 What's New in v1.1.0 (Enterprise Features)
- Zero UI Blocking:
WebWorkerAppenderoffloads heavy log formatting to a background thread. - Offline-First Sync:
HttpAppendernow uses Exponential Backoff and queues logs when offline. Tab-close safety viasendBeacon. - Crash Recovery:
IndexedDbAppendersafely stores logs locally to survive browser crashes. - Data Masking: Built-in sanitizer automatically masks PII (Credit Cards, Passwords, Emails).
- DDoS/Loop Protection:
BurstFilteracts 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 —
PatternLayoutandJsonLayoutwith 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-jsor 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.
