JavaScript SDK

Official JavaScript/TypeScript SDK for LogFlux with encrypted logging, resilient architecture, and production-ready features

The LogFlux JavaScript SDK provides a secure, high-performance way to send encrypted logs to LogFlux from your JavaScript and TypeScript applications.

πŸ“š View full documentation and examples on GitHub β†’

Installation

1
npm install @logflux/logflux-js-sdk

Quick Start

Ultra-Simple Usage (2 lines!)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const logflux = require('@logflux/logflux-js-sdk');

async function main() {
    // Initialize LogFlux (one time setup)
    logflux.init('https://<customer-id>.ingest.<region>.logflux.io', 'my-app', 'lf_your_api_key', 'your-secret');
    
    // Use it with proper log levels
    await logflux.info('User login successful');
    await logflux.warn('Rate limit approaching');
    await logflux.error('Database connection failed');
    
    await logflux.close();
}

Production-Ready Setup

1
2
export LOGFLUX_API_KEY="lf_your_api_key"
export LOGFLUX_SERVER_URL="https://<customer-id>.ingest.<region>.logflux.io"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const { ResilientClient } = require('@logflux/logflux-js-sdk');

async function main() {
    // Create resilient client from environment variables
    const client = ResilientClient.createFromEnv('production-server', 'your-encryption-secret');
    
    // Send logs - they're queued and sent asynchronously
    await client.info('Application started successfully');
    await client.error('Database connection failed - will retry');
    
    // Check statistics
    const stats = client.getStats();
    console.log(`Sent: ${stats.totalSent}, Failed: ${stats.totalFailed}, Queued: ${stats.queueSize}`);
    
    // Flush ensures all logs are sent before shutdown
    await client.flush(10000);
    await client.close();
}

Key Features

  • Strong Encryption: AES-256-GCM encryption via RSA handshake
  • Resilient Architecture: In-memory queuing, automatic retries, failsafe mode
  • High Performance: Async processing with configurable worker pools
  • Built-in Statistics: Monitor performance and queue health
  • Logger Adapters: Drop-in replacements for console, Winston, Bunyan, and Pino
  • TypeScript Support: Full type definitions included

Configuration

Environment Variables

1
2
3
4
5
6
7
8
9
# Required
export LOGFLUX_API_KEY="lf_your_api_key"
export LOGFLUX_SERVER_URL="https://<customer-id>.ingest.<region>.logflux.io"

# Optional
export LOGFLUX_QUEUE_SIZE="1000"
export LOGFLUX_FLUSH_INTERVAL="5"        # seconds
export LOGFLUX_WORKER_COUNT="2"
export LOGFLUX_FAILSAFE_MODE="true"

From Environment

1
2
// Create client from environment variables
const client = ResilientClient.createFromEnv('my-app', 'your-secret-key');

Log Levels

Level Value Method Description
Debug 0 .debug() Detailed diagnostic information
Info 1 .info() General informational messages
Warn 2 .warn() Warning messages
Error 3 .error() Error events
Fatal 4 .fatal() Critical system failures

Logger Adapters

Console Adapter

1
2
3
4
5
6
7
8
9
const { ResilientClient, ConsoleAdapter } = require('@logflux/logflux-js-sdk');

const client = ResilientClient.createFromEnv('my-app', 'secret');
const adapter = new ConsoleAdapter(client);
adapter.replaceGlobalConsole();

// Now all console calls go to LogFlux
console.log('This goes to LogFlux');
console.error('Error message');

Winston Adapter

1
2
3
4
5
6
7
8
9
const { ResilientClient, createWinstonLogger } = require('@logflux/logflux-js-sdk');

const client = ResilientClient.createFromEnv('my-app', 'secret');
const logger = createWinstonLogger(client);

// Use like Winston
logger.info('Winston info message');
logger.error('Winston error message');
logger.info('User action', { userId: 123, action: 'login' });

Express.js Integration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const express = require('express');
const { ResilientClient } = require('@logflux/logflux-js-sdk');

const app = express();
const client = ResilientClient.createFromEnv('web-server', 'your-secret');

app.use(async (req, res, next) => {
    const start = Date.now();
    
    await client.info(JSON.stringify({
        event: 'request_start',
        method: req.method,
        path: req.path
    }));
    
    res.on('finish', async () => {
        await client.info(JSON.stringify({
            event: 'request_end',
            method: req.method,
            path: req.path,
            status: res.statusCode,
            duration: Date.now() - start
        }));
    });
    
    next();
});

TypeScript Support

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import { ResilientClient, LogLevel, ClientStats } from '@logflux/logflux-js-sdk';

const client = new ResilientClient({
    serverUrl: 'https://<customer-id>.ingest.<region>.logflux.io',
    node: 'my-app',
    apiKey: 'lf_your_api_key',
    secret: 'your-encryption-secret',
    queueSize: 1000,
    failsafeMode: true,
});

await client.info('TypeScript message');

const stats: ClientStats = client.getStats();
console.log(`Sent: ${stats.totalSent}, Failed: ${stats.totalFailed}`);

Best Practices

Use Resilient Client in Production

1
2
3
4
5
6
7
8
const client = new ResilientClient({
    serverUrl: 'https://<customer-id>.ingest.<region>.logflux.io',
    node: 'production-server',
    apiKey: 'lf_your_api_key',
    secret: 'your-encryption-secret',
    failsafeMode: true,  // Never crash your app
    queueSize: 1000,     // Buffer logs during network issues
});

Handle Graceful Shutdown

1
2
3
4
5
6
7
8
async function gracefulShutdown() {
    await client.flush(10000);
    await client.close();
    process.exit(0);
}

process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);

Structure Your Logs

1
2
3
4
5
6
7
8
9
// Good: Structured JSON for better searchability
await client.info(JSON.stringify({
    event: 'user_login',
    user_id: '12345',
    success: true
}));

// Avoid: Unstructured text
await client.info('User 12345 logged in successfully');

Common Use Cases

Error Tracking

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
try {
    await processPayment(amount);
    await client.info(JSON.stringify({
        event: 'payment_success',
        amount: amount
    }));
} catch (error) {
    await client.error(JSON.stringify({
        event: 'payment_error',
        error: error.message,
        amount: amount
    }));
    throw error;
}

Database Operations

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
async function updateUser(userId, data) {
    const start = Date.now();
    
    try {
        await db.updateUser(userId, data);
        await client.info(JSON.stringify({
            event: 'db_query_success',
            table: 'users',
            duration: Date.now() - start
        }));
    } catch (error) {
        await client.error(JSON.stringify({
            event: 'db_query_error',
            table: 'users',
            error: error.message
        }));
        throw error;
    }
}

Requirements

  • Node.js: 14.0.0 or later
  • TypeScript: Full support with type definitions
  • Dependencies: Minimal - optimized for production use

Support