LogstackLogstack

JavaScript Configuration

Configure logstack-js — environments, captureConsole, batching, retries, and more.

JavaScript configuration

Deep-dive for logstack-js. For other languages see Go configuration and Python configuration.

Full configuration

import { createLogStack } from "logstack-js";
 
const logstack = createLogStack({
  // Required: Your project API key
  apiKey: process.env.LOGSTACK_API_KEY!,
 
  // API endpoint (defaults to Logstack cloud)
  endpoint: "https://api.logstack.tech",
 
  // Environment mode: 'development' | 'production' | 'staging' | 'test'
  // Controls console output — network shipping is independent (see below).
  // Omit to auto-detect (Vite import.meta.env → NODE_ENV → localhost).
  // environment: "development",
 
  // Console-only locally when no API key is configured
  disabled: !process.env.LOGSTACK_API_KEY,
 
  // Also log to console in production mode
  consoleInProduction: false,
 
  // Auto-capture context like URL, route, user agent
  captureContext: true,
 
  // Number of logs to buffer before auto-sending
  batchSize: 100,
 
  // Auto-flush interval in milliseconds
  flushInterval: 5000,
 
  // Maximum retry attempts for failed requests
  maxRetries: 3,
 
  // Error callback for failed log submissions
  onError: (error, logs) => {
    console.error("Failed to send logs:", error);
    // Optionally persist logs locally for later retry
    persistLogsLocally(logs);
  },
});

Configuration Options

apiKey (required)

Your project API key from the Logstack dashboard.

apiKey: "ls_live_abc123xyz789";

Use environment variables to store API keys. Never hardcode them in source code.

environment

Controls console output (pretty-printing for explicit SDK methods) and the environment label on each ingest batch. Network shipping is controlled separately by apiKey and disabled.

ValueConsole outputShips to server (if apiKey set, disabled: false)
developmentColored console output (default on)Yes
productionOff by default (consoleInProduction)Yes
stagingSame as productionYes
testConsole onYes

When omitted, the SDK auto-detects in this order:

  1. Vite / modern bundlersimport.meta.env.DEV, import.meta.env.MODE, import.meta.env.PROD
  2. process.env.NODE_ENV — Node and bundler define (accessed so Vite can replace it)
  3. Local browser hostslocalhost, 127.0.0.1, [::1], *.localhost, *.localdevelopment
  4. Otherwise production
// Omit and let the SDK detect (recommended for Vite + Node)
// environment: auto
 
// Or set explicitly
environment: "production",
// environment: import.meta.env.MODE as "development" | "production",

Older SDK versions only checked NODE_ENV behind a typeof process guard. Under Vite that guard often failed in the browser, so the client defaulted to production and explicit logstack.info(...) calls shipped to the API but did not pretty-print to the console. Upgrade to logstack-js ≥ 1.0.3, or pass environment: "development" / consoleInProduction: true explicitly.

Console and network are decoupled. Use disabled: true for console-only mode when you have no API key locally — you still get colored terminal output.

disabled

When true, logs are written to the console (unless silent: true) but never sent to the server. Use this for local development without an API key:

disabled: !process.env.LOGSTACK_API_KEY,

consoleInProduction

Whether to also output logs to console when in production mode.

consoleInProduction: true, // Useful for debugging production issues

captureContext

Automatically capture contextual information like URL, route, and user agent.

captureContext: true, // Default

When enabled in browser environments, Logstack automatically captures:

  • url — Current page URL
  • route — URL pathname
  • userAgent — Browser user agent string

This is the killer feature for effortless log collection.

When true (the default), Logstack automatically intercepts all native console calls:

  • console.log, console.info, console.debug
  • console.warn
  • console.error
  • console.trace
  • console.assert (failed assertions are captured as error level)

The original console output always happens first, then a structured log entry with source: "console" is forwarded to Logstack (and appears in your dashboard, mobile app, and can trigger alerts).

No need to replace every console.log in your codebase. Drop the SDK in and you get comprehensive coverage immediately for both dev and prod.

const logstack = createLogStack({
  apiKey: "...",
  // captureConsole: true  ← default, you can omit this line
});
 
// These are now captured automatically:
console.log("User clicked", { button: "checkout" });
console.error("Payment failed", err);
console.assert(user != null, "User must exist");

To opt out (rare):

captureConsole: false,

Use explicit logstack.info("msg", { rich: "metadata" }) when you want full control + structured fields. Both paths work great together.

endpoint

API endpoint URL. Use this for self-hosted instances.

EnvironmentURL
Production (default)https://api.logstack.tech
Self-hostedhttps://logs.your-domain.com
endpoint: process.env.LOGSTACK_ENDPOINT || "https://api.logstack.tech";

batchSize

Number of logs to buffer before automatically sending.

ValueBehavior
1Send immediately (higher latency, more requests)
100Default, good balance
500High-throughput applications
batchSize: 100;

flushInterval

How often to send buffered logs, in milliseconds.

flushInterval: 5000; // 5 seconds (default)

Logs are sent when either batchSize is reached OR flushInterval elapses, whichever comes first.

maxRetries

Maximum retry attempts for failed HTTP requests.

maxRetries: 3; // Default

Retries use exponential backoff: 200ms → 400ms → 800ms

onError

Callback function when log submission fails after all retries.

onError: (error: Error, logs: LogEntry[]) => {
  // Log to console as fallback
  console.error("Logstack error:", error.message);
 
  // Persist to local storage or file
  saveToLocalStorage(logs);
 
  // Send to error tracking service
  Sentry.captureException(error, { extra: { logCount: logs.length } });
};

Context Management

Set persistent context that applies to all subsequent logs:

// Set context for a request
logstack.setContext({
  url: "/api/users",
  method: "POST",
  requestId: "req_abc123",
  component: "UserService",
  ip: "192.168.1.1",
});
 
// All logs will now include this context
logstack.info("Processing request");
logstack.info("User created");
 
// Clear context when done
logstack.clearContext();

Context Properties

PropertyDescriptionExample
urlPage URL or API endpoint'/api/users'
routeRoute path pattern'/users/:id'
methodHTTP method'POST'
userAgentBrowser/client user agent'Mozilla/5.0...'
ipClient IP address'192.168.1.1'
requestIdRequest tracing ID'req_abc123'
componentComponent or module name'PaymentService'

Environment-Specific Configuration

Development

const logstack = createLogStack({
  apiKey: process.env.LOGSTACK_API_KEY!,
  environment: "development", // Console only
});
 
// Logs appear in terminal with colors:
// INFO     2026-01-30 14:23:15.234 [/api/users] - User created

Production

const logstack = createLogStack({
  apiKey: process.env.LOGSTACK_API_KEY!,
  environment: "production",
  batchSize: 100,
  flushInterval: 5000,
  maxRetries: 5,
  onError: (error, logs) => {
    errorReporter.capture(error);
    backupQueue.push(logs);
  },
});

Staging with Console Output

const logstack = createLogStack({
  apiKey: process.env.LOGSTACK_API_KEY!,
  environment: "staging",
  consoleInProduction: true, // See logs in terminal AND send to server
});

High-Throughput

const logstack = createLogStack({
  apiKey: process.env.LOGSTACK_API_KEY!,
  batchSize: 500, // Larger batches
  flushInterval: 10000, // Less frequent flushes
});

Graceful Shutdown

Always handle process termination to avoid losing logs:

// Node.js
process.on("SIGTERM", async () => {
  console.log("Shutting down...");
  await logstack.close();
  process.exit(0);
});
 
process.on("SIGINT", async () => {
  await logstack.close();
  process.exit(0);
});
 
// Serverless (flush at end of handler)
export async function handler(event) {
  try {
    // Your logic here
    logstack.info("Request processed");
  } finally {
    await logstack.flush();
  }
}

TypeScript Types

import type {
  LogStackConfig,
  LogLevel,
  LogEntry,
  LogStackClient,
} from "logstack-js";
 
const options: LogStackConfig = {
  apiKey: "ls_live_xxx",
  batchSize: 100,
};
 
const logstack: LogStackClient = createLogStack(options);