lognexis-node
v1.0.2
Published
Official LogNexis Node.js SDK — AI-powered API monitoring with Express middleware, automatic log capture, batch ingestion, and anomaly detection.
Maintainers
Readme
@lognexis/node
Official Node.js SDK for LogNexis — AI-powered API monitoring with Express middleware, automatic log capture, batch ingestion, and anomaly detection.
Features
- ⚡ Zero-config Express middleware — drop in one line, capture everything
- 📦 Intelligent batching — configurable batch size & flush interval
- 🔁 Exponential backoff retries — resilient to transient network issues
- 🔒 Automatic data redaction — headers, body fields, and sensitive values
- 🏷️ Dynamic tag injection — attach custom context per-request
- 🛑 Graceful shutdown — flush remaining logs before process exit
- 🧩 CJS + ESM + TypeScript — works in any Node.js project setup
Installation
npm install @lognexis/nodePeer dependency:
express >= 4.0.0(optional — only required for middleware usage)
Quick Start
Express Middleware (Recommended)
const express = require('express');
const { expressMiddleware } = require('@lognexis/node');
const app = express();
// Add LogNexis monitoring — place BEFORE your routes
app.use(expressMiddleware({
apiKey: 'ak_your_project_api_key', // Get from LogNexis dashboard
captureBody: true, // Capture request/response bodies
excludePaths: ['/health', '/favicon.ico'],
debug: false, // Set true during development
}));
app.get('/api/users', (req, res) => {
res.json({ users: [] });
});
app.listen(3000);Manual Capture
const { LogNexisClient } = require('@lognexis/node');
const client = new LogNexisClient({
apiKey: 'ak_your_project_api_key',
});
// Capture a log manually
client.capture({
endpoint: '/api/payment',
method: 'POST',
statusCode: 200,
latency: 142,
ipAddress: '203.0.113.42',
userAgent: 'Mozilla/5.0 ...',
tags: ['payment', 'production'],
});
// Flush immediately
await client.flush();ESM / TypeScript
import { expressMiddleware, LogNexisClient } from '@lognexis/node';
// or subpath import:
import { expressMiddleware } from '@lognexis/node/express';Configuration
expressMiddleware(options)
| Option | Type | Default | Description |
|---|---|---|---|
| apiKey | string | required | Your LogNexis project API key |
| baseUrl | string | production URL | LogNexis server URL |
| captureBody | boolean | false | Capture request/response bodies |
| captureHeaders | boolean | true | Capture request headers |
| maxBodySize | number | 2048 | Max body bytes to capture |
| batchSize | number | 25 | Logs per batch before auto-flush |
| flushInterval | number | 5000 | Auto-flush interval (ms) |
| maxRetries | number | 3 | Retry attempts on failure |
| maxQueueSize | number | 1000 | Max buffered logs before dropping |
| timeout | number | 10000 | HTTP timeout (ms) |
| excludePaths | string[] | ['/health', ...] | Paths to skip |
| includePaths | string[] | null | Only capture these paths |
| redactHeaders | string[] | ['authorization', 'cookie', ...] | Headers to redact |
| redactBodyFields | string[] | ['password', 'token', ...] | Body fields to redact |
| getTags | (req, res) => string[] | null | Dynamic tag injection |
| beforeSend | (logs) => logs | null | Transform logs before send |
| onError | (err) => void | null | Custom error handler |
| debug | boolean | false | Enable debug logging |
LogNexisClient(options)
Same options as above minus middleware-specific ones (captureBody, excludePaths, etc.).
Advanced Usage
Dynamic Tags
app.use(expressMiddleware({
apiKey: 'ak_your_api_key',
getTags: (req, res) => {
const tags = [req.method];
if (res.statusCode >= 500) tags.push('error');
if (req.user?.plan === 'pro') tags.push('pro-user');
return tags;
},
}));Transform Before Send
app.use(expressMiddleware({
apiKey: 'ak_your_api_key',
beforeSend: (logs) => {
// Add environment tag to every log
return logs.map(log => ({
...log,
tags: [...(log.tags || []), process.env.NODE_ENV],
}));
},
}));Graceful Shutdown
const monitor = expressMiddleware({ apiKey: 'ak_your_api_key' });
app.use(monitor);
process.on('SIGTERM', async () => {
await monitor.shutdown(); // Flushes remaining logs
process.exit(0);
});Access Stats
const monitor = expressMiddleware({ apiKey: 'ak_your_api_key' });
app.use(monitor);
// Later...
console.log(monitor.getStats());
// { sent: 1240, failed: 0, dropped: 0, retries: 2, queued: 3 }How It Works
Your Express App
│
▼
LogNexis Middleware
├── Intercepts every request/response
├── Measures latency with high-res timer
├── Sanitizes sensitive headers & body fields
└── Enqueues log entry
│
▼
In-memory Queue
├── Auto-flushes every 5s (configurable)
├── Batch-flushes at 25 logs (configurable)
└── Drops oldest on overflow
│
▼
POST /api/logs/:apiKey/batch
→ https://ai-api-monitoring-2.onrender.com
│
▼
LogNexis Dashboard
├── Real-time log stream
├── AI anomaly detection
└── Analytics & alertingAPI Reference
client.capture(logData)
Enqueue a single log entry manually.
client.flush() → Promise<void>
Immediately send all buffered logs.
client.shutdown() → Promise<void>
Flush and stop all timers. Call before process exit.
client.getStats() → ClientStats
Returns { sent, failed, dropped, retries, queued }.
License
MIT © LogNexis
