lognexis-node
v1.0.3
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
1. Get Your API Key
Sign up at lognexis.online and create a project to get your API key.
2. Express Middleware (Recommended)
const express = require('express');
const { expressMiddleware } = require('lognexis-node');
const app = express();
app.use(express.json());
// Add LogNexis monitoring — place BEFORE your routes
app.use(expressMiddleware({
apiKey: process.env.LOGNEXIS_API_KEY, // Your project API key
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, () => console.log('Server running on port 3000'));3. Manual Capture
const { LogNexisClient } = require('lognexis-node');
const client = new LogNexisClient({
apiKey: process.env.LOGNEXIS_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();4. ESM / TypeScript
import { expressMiddleware, LogNexisClient } from 'lognexis-node';Environment Variables
Add these to your .env file:
LOGNEXIS_API_KEY=ak_your_project_api_keyThen reference it in your code:
app.use(expressMiddleware({
apiKey: process.env.LOGNEXIS_API_KEY,
}));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 |
new LogNexisClient(options)
| Option | Type | Default | Description |
|---|---|---|---|
| apiKey | string | required | Your LogNexis project API key |
| baseUrl | string | production URL | LogNexis server URL |
| 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) |
| redactHeaders | string[] | ['authorization', 'cookie', 'set-cookie'] | Headers to redact |
| redactBodyFields | string[] | ['password', 'token', 'secret', 'creditCard', 'ssn'] | Body fields to redact |
| beforeSend | (logs) => logs | null | Transform logs before send |
| onError | (err) => void | null | Custom error handler |
| debug | boolean | false | Enable debug logging |
Advanced Usage
Dynamic Tags
app.use(expressMiddleware({
apiKey: process.env.LOGNEXIS_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: process.env.LOGNEXIS_API_KEY,
beforeSend: (logs) => {
// Add environment tag to every log
return logs.map(log => ({
...log,
tags: [...(log.tags || []), process.env.NODE_ENV],
}));
},
}));Custom Error Handler
app.use(expressMiddleware({
apiKey: process.env.LOGNEXIS_API_KEY,
onError: (err) => {
// Send to your error tracking service
console.error('LogNexis SDK error:', err.message);
},
}));Graceful Shutdown
const monitor = expressMiddleware({
apiKey: process.env.LOGNEXIS_API_KEY,
});
app.use(monitor);
process.on('SIGTERM', async () => {
await monitor.shutdown(); // Flushes remaining logs
process.exit(0);
});Access Stats
const monitor = expressMiddleware({
apiKey: process.env.LOGNEXIS_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
→ LogNexis Cloud
│
▼
LogNexis Dashboard
├── Real-time log stream
├── AI anomaly detection
└── Analytics & alertingAPI Reference
expressMiddleware(options) → LogNexisMiddleware
Creates Express middleware that automatically captures all HTTP requests and responses.
const { expressMiddleware } = require('lognexis-node');
const monitor = expressMiddleware({ apiKey: 'ak_...' });
app.use(monitor);Returns: A middleware function with additional properties:
monitor.client— the underlyingLogNexisClientinstancemonitor.shutdown()→Promise<void>— flush and stopmonitor.getStats()→ClientStats— current statistics
new LogNexisClient(options)
Creates a standalone client for manual log capture.
const { LogNexisClient } = require('lognexis-node');
const client = new LogNexisClient({ apiKey: 'ak_...' });client.capture(logData)
Enqueue a single log entry.
| Field | Type | Required | Description |
|---|---|---|---|
| endpoint | string | ✅ | API endpoint path (e.g. /api/users) |
| method | string | ✅ | HTTP method (GET, POST, etc.) |
| statusCode | number | ✅ | Response status code |
| latency | number | ✅ | Response time in milliseconds |
| ipAddress | string | — | Client IP address |
| userAgent | string | — | Client user agent |
| requestBody | object | — | Request body (auto-redacted) |
| responseBody | object | — | Response body (auto-redacted) |
| requestHeaders | object | — | Request headers (auto-redacted) |
| timestamp | string | — | ISO 8601 timestamp (defaults to now) |
| tags | string[] | — | Custom tags |
client.flush() → Promise<void>
Immediately send all buffered logs.
client.shutdown() → Promise<void>
Flush remaining logs and stop all timers. Call before process exit.
client.getStats() → ClientStats
Returns { sent, failed, dropped, retries, queued }.
Troubleshooting
Logs not appearing in dashboard?
- Check your API key — Make sure
LOGNEXIS_API_KEYis set correctly in your environment - Enable debug mode — Set
debug: trueto see SDK output in your console - Check path filters — Your routes may be matched by
excludePaths - Flush on exit — Ensure you call
monitor.shutdown()orclient.shutdown()before exiting
Getting rate limited (429)?
The SDK automatically retries with exponential backoff. If you're consistently hitting rate limits, reduce your batchSize or increase flushInterval.
License
MIT © LogNexis
