2.0.0 β€’ Published 5 months ago

@nxtwebmasters/nxt-smart-logger v2.0.0

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

πŸš€ NXT Smart Logger | Advanced Console Interceptor

npm license downloads

A sophisticated console interceptor that supercharges your logging capabilities with server integration, GTM support, context/meta injection, custom log levels, and reusable structured logs for modern applications.

✨ Features

  • πŸ”€ Batched Log Transmission - Optimize network calls with configurable batching
  • πŸ“Š GTM Integration - Seamless integration with Google Tag Manager
  • πŸ‘€ Contextual Logging - Attach user/session context automatically
  • ⚑ Multiple Destinations - Send logs to server, GTM, or both simultaneously
  • πŸ›‘οΈ Error Resilient - Automatic retries for failed transmissions
  • πŸ”„ Framework Agnostic - Works with Angular, React, Vue, or vanilla JS
  • 🧹 Custom Logging - Define your own log types and structured events
  • ✨ Extendable API - Inject tags, meta, or override per log call

πŸ“¦ Installation

npm install @nxtwebmasters/nxt-smart-logger
# or
yarn add @nxtwebmasters/nxt-smart-logger

πŸš€ Quick Start

import { ConsoleInterceptor } from "@nxtwebmasters/nxt-smart-logger";

const interceptor = new ConsoleInterceptor({
  batchSize: 10,
  flushInterval: 5000,
  contextProvider: () => ({
    userId: "USER123",
    sessionId: "SESSION456",
    appVersion: "1.0.0",
  }),
  serverLogger: async (logs) => {
    await fetch("https://yourserver.com/api/logs", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(logs),
    });
  },
});

const logger = interceptor.getLogger();
logger.info("User logged in");
logger.withTags(["auth"]).warn("Login attempt");
logger.withContext({ feature: "search" }).error("Search failed");
logger.withMeta({ region: "us-east-1" }).debug("Region-specific check");
logger.withAll({
  tags: ["api"],
  context: { feature: "checkout" },
  meta: { version: "2.1.0" },
}).error("API timeout");

interceptor.setContext({ userId: "ADMIN" });

βš™οΈ Configuration Options

OptionTypeDefaultDescription
batchSizenumber5Max logs per batch
flushIntervalnumber5000Max wait time (ms) between flushes
contextProvider() => object() => ({})Provides dynamic context
serverLogger(logs) => Promise<void>nullFunction to POST logs to your backend
customLevelsstring[][]Custom log levels (e.g. audit, track)
filterLevelsstring[]all levelsLog levels to capture from console
generateTraceId() => stringuuidv4Custom trace ID generator

🧩 Structured Log Format

{
  "level": "warn",
  "timestamp": "2025-05-31T12:34:56.789Z",
  "message": "Login failed {\"code\":401}",
  "tags": ["auth"],
  "context": {
    "userId": "USER123",
    "sessionId": "SESSION456",
    "feature": "login"
  },
  "meta": {
    "url": "https://nxtwebmasters.com/app",
    "userAgent": "Mozilla/5.0...",
    "traceId": "uuid-123",
    "sessionId": "SESSION456"
  },
  "data": {
    "code": 401
  }
}

πŸ”Œ Integration Examples β€” NXT Smart Logger

Here’s how to plug @nxtwebmasters/nxt-smart-logger into various environments:


βš›οΈ React Setup

// logger.ts
import { ConsoleInterceptor } from '@nxtwebmasters/nxt-smart-logger';

export const interceptor = new ConsoleInterceptor({
  contextProvider: () => ({
    userId: localStorage.getItem('userId'),
    sessionId: sessionStorage.getItem('sessId')
  }),
  serverLogger: async (logs) => {
    await fetch('/api/logs', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(logs),
    });
  }
});

export const logger = interceptor.getLogger();
// App.tsx
import { logger } from './logger';

function App() {
  useEffect(() => {
    logger.info('App mounted');
  }, []);
  return <h1>Welcome</h1>;
}

🧩 Vue Setup

// logger.ts
import { ConsoleInterceptor } from '@nxtwebmasters/nxt-smart-logger';

const interceptor = new ConsoleInterceptor({
  contextProvider: () => ({ userId: 'vue-user', role: 'admin' })
});

export const logger = interceptor.getLogger();
<script setup>
import { onMounted } from 'vue';
import { logger } from './logger';

onMounted(() => {
  logger.info('Vue component mounted');
});
</script>

πŸ–₯️ Node.js Setup (e.g., CLI apps or SSR)

import { ConsoleInterceptor } from '@nxtwebmasters/nxt-smart-logger';

const interceptor = new ConsoleInterceptor({
  enableGTM: false,
  enableServer: true,
  contextProvider: () => ({ env: 'node', pid: process.pid }),
  serverLogger: async (logs) => {
    console.log('Sending logs to API:', logs);
  }
});

const logger = interceptor.getLogger();
logger.info('CLI started');

Use the logger the same way across all frameworks:

logger.error('Something went wrong', { details: '...' })
logger.withTags(['startup']).info('App ready')

🌍 Works Anywhere

  • React (hooks, SSR, client)
  • Vue 2/3 (setup API or options API)
  • Vanilla JS / CDN
  • Node.js (CLI, workers, Express)

🌐 Browser Support

ChromeEdgeFirefoxSafari
Latest βœ”Latest βœ”Latest βœ”Latest βœ”

🀝 Contributing

We welcome contributions! Please see our Contribution Guidelines.

πŸ“œ License

MIT Β© NXT WebMasters

2.0.0

5 months ago

1.5.2

5 months ago

1.5.1

5 months ago

1.4.1

5 months ago

1.5.0

5 months ago

1.4.0

5 months ago

1.3.0

5 months ago

1.2.0

5 months ago

1.1.0

5 months ago

1.0.0

5 months ago