Node.js SDK

GitHub

Official Node.js SDK for LogWard with full TypeScript support, automatic batching, retry logic, and Express/Fastify middleware.

Installation

bash
npm install @logward-dev/sdk-node

# or with pnpm
pnpm add @logward-dev/sdk-node

# or with yarn
yarn add @logward-dev/sdk-node

Quick Start

typescript
import { LogWardClient } from '@logward-dev/sdk-node';

const client = new LogWardClient({
  apiUrl: 'http://localhost:8080',
  apiKey: 'lp_your_api_key_here',
});

// Send logs
client.info('api-gateway', 'Server started', { port: 3000 });
client.error('database', 'Connection failed', new Error('Timeout'));

// Graceful shutdown
process.on('SIGINT', async () => {
  await client.close();
  process.exit(0);
});

Features

  • ✅ Automatic batching with configurable size and interval
  • ✅ Retry logic with exponential backoff
  • ✅ Circuit breaker pattern for fault tolerance
  • ✅ Max buffer size with drop policy to prevent memory leaks
  • ✅ Query API for searching and filtering logs
  • ✅ Live tail with Server-Sent Events (SSE)
  • ✅ Trace ID context for distributed tracing
  • ✅ Global metadata added to all logs
  • ✅ Structured error serialization
  • ✅ Internal metrics (logs sent, errors, latency)
  • ✅ Express & Fastify middleware for auto-logging HTTP requests
  • ✅ Full TypeScript support with strict types

Configuration

typescript
const client = new LogWardClient({
  // Required
  apiUrl: 'http://localhost:8080',
  apiKey: 'lp_your_api_key',
  
  // Optional - Performance
  batchSize: 100,              // Max logs per batch (default: 100)
  batchInterval: 5000,         // Flush interval in ms (default: 5000)
  maxBufferSize: 10000,        // Max logs in buffer (default: 10000)
  
  // Optional - Reliability
  maxRetries: 3,               // Max retry attempts (default: 3)
  retryDelay: 1000,            // Initial retry delay in ms (default: 1000)
  circuitBreakerThreshold: 5,  // Failures before circuit opens (default: 5)
  circuitBreakerTimeout: 60000, // Circuit reset timeout in ms (default: 60000)
  
  // Optional - Metadata
  globalMetadata: {            // Added to all logs
    environment: 'production',
    version: '1.0.0'
  },
  
  // Optional - Debug
  debug: false                 // Enable debug logging (default: false)
});

Logging Methods

Basic Logging

typescript
// Log levels: debug, info, warn, error, critical
client.debug('service-name', 'Debug message', { detail: 'value' });
client.info('api-gateway', 'Request received', { method: 'GET', path: '/users' });
client.warn('cache', 'Cache miss', { key: 'user:123' });
client.error('database', 'Query failed', { query: 'SELECT *' });
client.critical('system', 'Out of memory', { used: '95%' });

Error Logging with Auto-Serialization

typescript
try {
  await riskyOperation();
} catch (error) {
  // Error is automatically serialized (stack trace, message, etc.)
  client.error('api', 'Operation failed', error);
}

Middleware Integration

Express Middleware

typescript
import express from 'express';
import { createExpressMiddleware } from '@logward-dev/sdk-node';

const app = express();

// Add LogWard middleware
app.use(createExpressMiddleware(client, {
  includeHeaders: true,       // Log request headers
  includeBody: false,         // Log request body (be careful with sensitive data)
  includeResponseTime: true   // Log response time
}));

app.get('/users', (req, res) => {
  // Your route logic
  res.json({ users: [] });
});

// Logs will be automatically sent for each request

Fastify Plugin

typescript
import Fastify from 'fastify';
import { fastifyLogWardPlugin } from '@logward-dev/sdk-node';

const fastify = Fastify();

// Register LogWard plugin
await fastify.register(fastifyLogWardPlugin, {
  client,
  includeHeaders: true,
  includeResponseTime: true
});

fastify.get('/users', async (request, reply) => {
  // Your route logic
  return { users: [] };
});

// Logs automatically sent for each request

Query API

typescript
// Search logs
const logs = await client.query({
  service: 'api-gateway',
  level: 'error',
  from: '2025-01-15T00:00:00Z',
  to: '2025-01-15T23:59:59Z',
  q: 'timeout',  // Full-text search
  limit: 100
});

console.log(`Found ${logs.total} error logs`);
logs.logs.forEach(log => {
  console.log(`[${log.time}] ${log.message}`);
});

Live Tail (Streaming)

typescript
// Stream logs in real-time
const stream = client.stream({
  service: 'api-gateway',
  level: 'error'
});

stream.on('log', (log) => {
  console.log('New log:', log);
});

stream.on('error', (error) => {
  console.error('Stream error:', error);
});

// Stop streaming
setTimeout(() => {
  stream.close();
}, 60000);

Best Practices

1. Always Close on Shutdown
Ensure logs are flushed before your application exits by calling await client.close() in shutdown handlers.
2. Use Global Metadata
Add environment, version, and other common fields as global metadata instead of repeating them in every log.
3. Enable Debug Mode in Development
Set debug: true during development to see SDK internal logs and troubleshoot issues.
4. Use Trace IDs for Request Correlation
Leverage trace IDs to correlate logs across distributed services for better debugging.