LogFlux JavaScript SDK

JavaScript Logo Node.js Logo

The official JavaScript/TypeScript SDK for LogFlux. Send logs, metrics, traces, events, and audit entries directly to the LogFlux cloud with end-to-end encryption from Node.js applications. The server never sees your plaintext data.

GitHub Repository ยท Release Notes

Key Features

  • End-to-end encryption – AES-256-GCM with RSA key exchange
  • 7 entry types – Log, Metric, Trace, Event, Audit, Telemetry, TelemetryManaged
  • Multipart binary transport – 33% less overhead than JSON + base64
  • Async by default – Non-blocking queue with background workers
  • Breadcrumbs – Automatic trail of recent events attached to error captures
  • Distributed tracing – Spans, child spans, trace header propagation
  • Scopes – Per-request context isolation
  • Full TypeScript – Complete type definitions included
  • Failsafe – SDK errors never crash your application
  • Zero runtime dependencies – Node.js 18+ built-ins only

Installation

1
npm install @logflux-io/logflux-js-sdk

Quick Start

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import { LogFlux } from '@logflux-io/logflux-js-sdk';

LogFlux.init({
    apiKey: 'eu-lf_your_api_key',
    source: 'my-service',
    environment: 'production',
    release: '1.2.3',
});

LogFlux.info('server started');

// Before process exit
await LogFlux.flush(2000);
LogFlux.close();

Entry Types

Log (Type 1)

Standard application logs with 8 severity levels.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
LogFlux.debug('cache miss for key users:123');
LogFlux.info('request processed');
LogFlux.warn('deprecated API called');
LogFlux.error('database connection failed');
LogFlux.critical('out of memory');

// With attributes
LogFlux.log(LogLevel.Error, 'query timeout', {
    'db.host': 'primary.db.internal',
    'duration_ms': '5023',
});

Metric (Type 2)

Counters, gauges, and distributions.

1
2
3
4
5
6
7
8
LogFlux.counter('http.requests.total', 1, {
    method: 'GET',
    status: '200',
});

LogFlux.gauge('system.cpu.usage', 85.2, {
    host: 'web-01',
});

Event (Type 4)

Discrete application events.

1
2
3
4
LogFlux.event('user.signup', {
    user_id: 'usr_987',
    plan: 'starter',
});

Audit (Type 5)

Immutable audit trail with Object Lock storage (365-day retention).

1
2
3
LogFlux.audit('record.deleted', 'usr_456', 'invoice', 'inv_789', {
    reason: 'customer_request',
});

Trace (Type 3)

Distributed tracing with span helpers.

1
2
3
4
5
6
7
const span = LogFlux.startSpan('http.server', 'GET /api/users');

const dbSpan = span.startChild('db.query', 'SELECT * FROM users');
// ... query ...
dbSpan.end();

span.end();

Telemetry (Types 6 and 7)

Device and sensor data. Type 6 is end-to-end encrypted, type 7 is server-side encrypted.

Error Capture

Capture JavaScript errors with automatic stack traces and breadcrumb trail.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try {
    await database.query(sql);
} catch (err) {
    LogFlux.captureError(err);

    // With extra context
    LogFlux.captureError(err, {
        sql,
        'db.host': 'primary',
    });
}

Breadcrumbs record a trail of events leading up to an error. They are automatically added for log and event calls, and attached to captureError.

1
2
3
4
5
6
7
8
LogFlux.info('loading config');          // auto breadcrumb
LogFlux.event('user.login');             // auto breadcrumb

LogFlux.addBreadcrumb('http', 'GET /api/users', {
    status: '200',
});

LogFlux.captureError(err);  // includes breadcrumb trail

Scopes

Per-request context isolation. Attributes set on a scope are merged into every entry.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
LogFlux.withScope((scope) => {
    scope.setUser('usr_456');
    scope.setRequest('GET', '/api/users', 'req_abc123');
    scope.setAttribute('tenant', 'acme-corp');

    scope.info('processing request');

    if (err) {
        scope.captureError(err);
    }
});

Trace Context Propagation

Propagate trace context across services via HTTP headers.

1
2
3
4
5
6
7
8
9
// Client: inject trace header
const span = LogFlux.startSpan('http.client', 'GET /api');
const headers = { 'X-LogFlux-Trace': span.traceHeader };
await fetch(url, { headers });

// Server: continue from incoming headers
const span = LogFlux.continueFromHeaders(req.headers, 'http.server', 'GET /api');
// ... handle request ...
span.end();

Express Middleware

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

app.use((req, res, next) => {
    const span = LogFlux.startSpan('http.server', `${req.method} ${req.path}`);
    span.setAttribute('http.method', req.method);
    span.setAttribute('http.url', req.originalUrl);

    res.on('finish', () => {
        span.setAttribute('http.status_code', String(res.statusCode));
        if (res.statusCode >= 500) span.setError(new Error(`HTTP ${res.statusCode}`));
        span.end();
    });

    next();
});

Configuration

Options

OptionTypeDefaultDescription
apiKeystringrequiredAPI key (<region>-lf_<key>)
sourcestringService name
environmentstringAttached to meta.environment
releasestringAttached to meta.release
queueSizenumber1000In-memory buffer capacity
batchSizenumber100Entries per HTTP request
flushIntervalnumber5000Auto-flush interval (ms)
workerCountnumber2Background workers
maxRetriesnumber3Max retry attempts
sampleRatenumber1.00.0-1.0, send probability
maxBreadcrumbsnumber100Ring buffer size
failsafebooleantrueNever crash host app
enableCompressionbooleantrueGzip before encryption

Environment Variables

1
LogFlux.initFromEnv('my-node');

Reads LOGFLUX_API_KEY, LOGFLUX_ENVIRONMENT, LOGFLUX_NODE, LOGFLUX_QUEUE_SIZE, LOGFLUX_BATCH_SIZE, LOGFLUX_KEY_PERSISTENCE, LOGFLUX_KEY_PERSISTENCE_PATH, LOGFLUX_KEY_ROTATION_DAYS, etc.

Key Persistence

The SDK persists AES encryption keys to disk by default, reusing them across restarts instead of performing a new handshake each time. This reduces key proliferation in the database and speeds up initialization.

OptionTypeDefaultDescription
keyPersistencebooleantrueEnable/disable key persistence
keyPersistencePathstring~/.logflux/sessions/Custom directory for session files
keyRotationIntervalMsnumber0 (never)Rotate key after this many milliseconds

Session files are stored at ~/.logflux/sessions/<hash>.json with 0600 permissions. If the cached key is rejected by the server (401/403), the SDK automatically re-handshakes and saves the new key.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Disable persistence (for ephemeral containers)
LogFlux.init({
    apiKey: 'eu-lf_your_key',
    keyPersistence: false,
});

// Custom path and 30-day rotation
LogFlux.init({
    apiKey: 'eu-lf_your_key',
    keyPersistencePath: '/var/lib/myapp/logflux/',
    keyRotationIntervalMs: 30 * 24 * 60 * 60 * 1000,
});

BeforeSend Hooks

Filter or modify entries before they are sent. Return null to drop.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
LogFlux.init({
    apiKey: 'eu-lf_...',
    beforeSendLog: (log) => {
        if (log.level === 8) return null;  // drop debug
        return log;
    },
    beforeSendAudit: (audit) => {
        delete audit.attributes?.ip;  // scrub PII
        return audit;
    },
});

Per-type hooks: beforeSendLog, beforeSendError, beforeSendMetric, beforeSendEvent, beforeSendAudit, beforeSendTrace, beforeSendTelemetry.

Sampling

1
LogFlux.init({ apiKey: '...', sampleRate: 0.1 });  // send 10%

Audit entries (type 5) are never sampled.

Security

  • Zero-knowledge: All payloads encrypted client-side with AES-256-GCM
  • RSA key exchange: AES keys negotiated via RSA-2048 OAEP handshake
  • Key zeroing: AES keys cleared from memory on close()
  • Bounded reads: All HTTP responses size-limited
  • Failsafe: SDK errors never crash the host application

Requirements

  • Node.js 18 or later
  • LogFlux account with API key

License

Elastic License 2.0 (ELv2) – free for all use except offering as a hosted or managed service to third parties.

Support

Disclaimer

The JavaScript and Node.js logos and trademarks are the property of Oracle Corporation and the OpenJS Foundation respectively. LogFlux is not affiliated with, endorsed by, or sponsored by Oracle Corporation or the OpenJS Foundation. The logos are used solely for identification purposes to indicate compatibility and integration capabilities.