Skip to content

Better Stack Transport Server Deno Bun

NPM Version

Transport Source

The Better Stack transport allows you to send logs to Better Stack's log management platform using their HTTP API. It provides a simple and efficient way to ship logs to Better Stack for centralized logging and analysis.

Installation

sh
npm install @loglayer/transport-betterstack loglayer
sh
pnpm add @loglayer/transport-betterstack loglayer
sh
yarn add @loglayer/transport-betterstack loglayer

Usage

  • Create a "Javascript / Node.js" log source in your Better Stack account.
  • In the "Data ingestion" tab of your source, find your source token and the ingesting host.
  • Add https:// in front of the ingesting host for the url parameter.
typescript
import { LogLayer } from "loglayer";
import { BetterStackTransport } from "@loglayer/transport-betterstack";

const logger = new LogLayer({
  transport: new BetterStackTransport({
    sourceToken: "<source token>",
    url: "https://<ingesting host>",
    onError: (err) => {
      console.error('Failed to send logs to Better Stack:', err);
    },
    onDebug: (entry) => {
      console.log('Log entry being sent to Better Stack:', entry);
    },
    onDebugReqRes: ({ req, res }) => {
      console.log("=== HTTP Request ===");
      console.log("URL:", req.url);
      console.log("Method:", req.method);
      console.log("Headers:", JSON.stringify(req.headers, null, 2));
      console.log("Body:", typeof req.body === "string" ? req.body : `[Uint8Array: ${req.body.length} bytes]`);
      console.log("=== HTTP Response ===");
      console.log("Status:", res.status, res.statusText);
      console.log("Headers:", JSON.stringify(res.headers, null, 2));
      console.log("Body:", res.body);
      console.log("===================");
    },
  }),
});

// Start logging
logger.info("Hello from LogLayer!");
logger.withMetadata({ userId: "123" }).info("User logged in");

Configuration Options

Required Parameters

NameTypeDescription
sourceTokenstringYour Better Stack source token for authentication (found in the "Data ingestion" tab of your "Javascript / Node.js" source)
urlstringBetter Stack ingestion host URL (add "https://" in front of the ingestion host from the "Data ingestion" tab of your "Javascript / Node.js" source)

Optional Parameters

NameTypeDefaultDescription
includeTimestampbooleantrueWhether to include timestamp in the log payload
timestampFieldstring"dt"Custom field name for the timestamp
onError(error: Error) => void-Callback for error handling
onDebug(entry: Record<string, any>) => void-Callback for debugging log entries
level"trace" | "debug" | "info" | "warn" | "error" | "fatal""trace"Minimum log level to process
enabledbooleantrueIf false, the transport will not send logs to the logger
idstring-A user-defined identifier for the transport

HTTP Transport Optional Parameters

General Parameters

NameTypeDefaultDescription
enabledbooleantrueWhether the transport is enabled
level"trace" | "debug" | "info" | "warn" | "error" | "fatal""trace"Minimum log level to process. Logs below this level will be filtered out
methodstring"POST"HTTP method to use for requests
headersRecord<string, string> | (() => Record<string, string>){}Headers to include in the request. Can be an object or a function that returns headers
contentTypestring"application/json"Content type for single log requests. User-specified headers take precedence
compressionbooleanfalseWhether to use gzip compression
maxRetriesnumber3Number of retry attempts before giving up
retryDelaynumber1000Base delay between retries in milliseconds
respectRateLimitbooleantrueWhether to respect rate limiting by waiting when a 429 response is received
maxLogSizenumber1048576Maximum size of a single log entry in bytes (1MB)
maxPayloadSizenumber5242880Maximum size of the payload (uncompressed) in bytes (5MB)
enableNextJsEdgeCompatbooleanfalseWhether to enable Next.js Edge compatibility

Debug Parameters

NameTypeDefaultDescription
onError(err: Error) => void-Error handling callback
onDebug(entry: Record<string, any>) => void-Debug callback for inspecting log entries before they are sent
onDebugReqRes(reqRes: { req: { url: string; method: string; headers: Record<string, string>; body: string | Uint8Array }; res: { status: number; statusText: string; headers: Record<string, string>; body: string } }) => void-Debug callback for inspecting HTTP requests and responses. Provides complete request/response details including headers and body content

Batch Parameters

NameTypeDefaultDescription
batchContentTypestring"application/json"Content type for batch log requests. User-specified headers take precedence
enableBatchSendbooleantrueWhether to enable batch sending
batchSizenumber100Number of log entries to batch before sending
batchSendTimeoutnumber5000Timeout in milliseconds for sending batches regardless of size
batchSendDelimiterstring"\n"Delimiter to use between log entries in batch mode
batchMode"delimiter" | "field" | "array""delimiter"Batch mode for sending multiple log entries. "delimiter" joins entries with a delimiter, "field" wraps an array of entries in an object with a field name, "array" sends entries as a plain JSON array of objects
batchFieldNamestring-Field name to wrap batch entries in when batchMode is "field"

For more details on these options, see the HTTP transport documentation.

Changelog

View the changelog here.