Skip to content

Send logs from Node.js with Pino

Ship Pino logs from a Node.js application to Logbrook.

Updated

Run the Pino example against your Logbrook server, then copy its logger setup into your own application. It batches records, retries failed requests and waits for delivery on shutdown.

The code is in examples/pino-logger. It uses Pino and pino-http-transport.

Requirements

  • Node.js 24 or later.
  • A running Logbrook server and its ingestion token. See the quickstart. Read and admin tokens can’t ingest.
  • To check the results, the read token and the logbrook CLI.

The example pins Pino 10.4.0, pino-http-transport 2.1.0 and thread-stream 4.2.0. The shutdown helper below relies on thread-stream’s delivery-aware flush.

Run the example

  1. Install dependencies

    From a checkout of the Logbrook repository:

    cd examples/pino-logger
    npm ci
  2. Set the connection

    export LOGBROOK_URL=http://127.0.0.1:3100
    export LOGBROOK_INGEST_TOKEN='<your ingestion token>'
    export LOGBROOK_INDEX=pino-demo

    LOGBROOK_URL is the server’s base URL. It can include a reverse-proxy path prefix such as https://logs.example.com/logbrook, but not credentials, a query string or a fragment. Use HTTPS for any server that isn’t on your machine.

  3. Send four records

    npm start

    This runs basic.mjs, which logs four records and closes the transport.

  4. Check the records

    The logbrook CLI doesn’t read the example’s .env file. Export the read token in your shell:

    export LOGBROOK_READ_TOKEN='<your read token>'
    
    logbrook query "$LOGBROOK_INDEX" --since 15m --service checkout --json
    logbrook count "$LOGBROOK_INDEX" --since 15m --service checkout

    After one run against a new index the count is 4. Each further run adds four.

The transport sends POST /indexes/pino-demo/logs/ingest. If pino-demo doesn’t exist, the first write creates it, as long as the token may write to it and the server has a free index slot. See send logs over HTTP.

Use a .env file

To keep settings in a file, copy the template and set LOGBROOK_INGEST_TOKEN:

cp .env.example .env

npm start and npm run bulk load .env when it exists. Variables exported in your shell win over the file. The file takes the variables listed under Settings.

Configure the logger

logger.mjs validates the environment, builds the ingest URL, starts the transport worker and returns the logger with a close() function.

logger.mjsjs
import { once } from 'node:events';
import pino from 'pino';

export function integerSetting(env, name, fallback, min = 1, max = 2_147_483_647) {
  const raw = env[name] ?? String(fallback);
  const value = Number(raw);

  // Reject coercible values such as empty strings, fractions, and exponent notation.
  if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value < min || value > max) {
    throw new Error(`${name} must be an integer between ${min} and ${max}`);
  }

  return value;
}

export async function createLogger(env = process.env) {
  const token = env.LOGBROOK_INGEST_TOKEN;
  if (!token || /[\r\n]/.test(token)) {
    throw new Error(
      'Set LOGBROOK_INGEST_TOKEN to the ingestion credential configured on your server',
    );
  }

  let base;
  try {
    base = new URL(env.LOGBROOK_URL ?? 'http://127.0.0.1:3100');
  } catch {
    throw new Error('LOGBROOK_URL must be a valid HTTP(S) server URL');
  }

  if (
    !['http:', 'https:'].includes(base.protocol) ||
    base.username ||
    base.password ||
    base.search ||
    base.hash
  ) {
    throw new Error('LOGBROOK_URL must use HTTP(S) without credentials, a query, or a fragment');
  }

  const index = env.LOGBROOK_INDEX ?? 'pino-demo';
  if (!/^[a-z0-9][a-z0-9_-]{0,62}$/.test(index)) {
    throw new Error(
      'LOGBROOK_INDEX must be 1–63 lowercase letters, digits, underscores or hyphens, starting with a letter or digit',
    );
  }

  const service = env.LOG_SERVICE ?? 'checkout';
  if (!service || Buffer.byteLength(service) > 4096) {
    throw new Error('LOG_SERVICE must be a nonempty string of at most 4096 UTF-8 bytes');
  }

  const batchSize = integerSetting(env, 'BATCH_SIZE', 250, 1, 1000);
  const maxBufferSize = integerSetting(env, 'MAX_BUFFER_SIZE', 10_000);
  if (maxBufferSize < batchSize) {
    throw new Error('MAX_BUFFER_SIZE must be at least BATCH_SIZE');
  }

  // Create one worker per application, shared by all child loggers.
  const transport = pino.transport({
    target: 'pino-http-transport',
    options: {
      url: `${base.href.replace(/\/$/, '')}/indexes/${index}/logs/ingest`,
      headers: { authorization: `Bearer ${token}` },
      batchSize,
      batchInterval: integerSetting(env, 'BATCH_INTERVAL_MS', 1000),
      maxBufferSize,
      timeout: integerSetting(env, 'HTTP_TIMEOUT_MS', 1500),
      maxRetries: integerSetting(env, 'MAX_RETRIES', 2, 0, 10),
      retryDelay: integerSetting(env, 'RETRY_DELAY_MS', 250, 0),
      silent: false,
    },
  });

  // Keep the first worker error, including errors arriving after startup.
  let failure;
  transport.on('error', (error) => {
    failure ??= error;
  });

  await once(transport, 'ready');

  // Keep short-lived scripts alive until close() completes.
  transport.ref();

  const logger = pino({ name: 'pino-example', level: 'info' }, transport).child({ service });
  let closing;

  return {
    logger,

    throwIfFailed() {
      if (failure) {
        throw failure;
      }
    },

    close() {
      // Share shutdown work so repeated calls cannot end the worker twice.
      closing ??= (async () => {
        if (!transport.closed) {
          // Deliver the backlog before end() starts its blocking shutdown budget.
          try {
            await new Promise((resolve, reject) => {
              transport.flush((error) => {
                if (error) {
                  reject(error);
                } else {
                  resolve();
                }
              });
            });
          } finally {
            // Always release the worker, including after a failed delivery flush.
            if (!transport.closed) {
              const closed = once(transport, 'close');
              transport.end();
              await closed;
            }
          }
        }

        if (failure) {
          throw failure;
        }
      })();

      return closing;
    },
  };
}

Create one logger and transport per process, never one per request. Use child loggers to add request context; they share the worker thread and HTTP queue.

basic.mjsjs
import { createLogger } from './logger.mjs';

try {
  const { logger, close } = await createLogger();

  try {
    logger.info('Pino is connected to Logbrook');

    // Child loggers share the worker and HTTP batch queue.
    const requestLog = logger.child({ requestId: 'req-demo-1', orderId: 'ord-42' });
    requestLog.info({ durationMs: 42, statusCode: 200 }, 'Checkout completed');
    requestLog.warn({ durationMs: 1250 }, 'Payment provider was slow');
    requestLog.error({ err: new Error('Demo payment failure') }, 'Payment failed');
  } finally {
    // Flush the last partial batch, even though it is smaller than BATCH_SIZE.
    await close();
  }

  console.log(
    'Produced 4 records and closed the transport. Query the pino-demo index (or LOGBROOK_INDEX).',
  );
} catch (error) {
  // Do not log transport failures through the same failed transport.
  console.error(`Pino example failed: ${error.message}`);
  process.exitCode = 1;
}

createLogger() also returns throwIfFailed(), which throws if the transport has reported an error. bulk.mjs calls it to stop producing after a failure.

How Pino fields map to Logbrook

Pino field Logbrook field
time, level, msg event_time, level, message
service, name, hostname, pid service, logger, host, pid
requestId, orderId, durationMs, err and any other field Inside attributes
The ingestion token source. A payload field can’t override it.

The example sets name to pino-example and service from LOG_SERVICE. Keep Pino’s defaults for the fields Logbrook requires:

  • Numeric levels. Don’t format levels as labels such as "info".
  • Unix-millisecond timestamps. Don’t switch to ISO time strings.
  • A message on every call. Pino omits msg when you log a plain object without a message string, and Logbrook rejects events without one.

Pino’s err serializer records the error’s type, message and stack. Every string value, stack traces included, must fit the server’s default field limit of 4,096 bytes, or the whole batch is rejected. Log selected fields rather than whole request bodies or headers, and use Pino’s redaction for anything sensitive.

Settings

All settings are environment variables. The example overrides several transport defaults.

Variable Example default Transport default Purpose
LOGBROOK_URL http://127.0.0.1:3100 Server base URL
LOGBROOK_INDEX pino-demo Destination index
LOGBROOK_INGEST_TOKEN Required Ingestion token
LOG_SERVICE checkout Value of the service field
BATCH_SIZE 250 100 Records per HTTP request, 1 to 1,000
BATCH_INTERVAL_MS 1000 5000 Wait before sending a partial batch
MAX_BUFFER_SIZE 10000 100000 Waiting records, at least BATCH_SIZE
HTTP_TIMEOUT_MS 1500 2500 Timeout for each HTTP attempt
MAX_RETRIES 2 2 Retries after the first attempt, 0 to 10
RETRY_DELAY_MS 250 1000 First retry delay. It doubles each retry, capped at the timeout.
LOG_COUNT 10000 Records produced by npm run bulk
LOG_RATE 1000 Target records per second for npm run bulk
RUN_ID Random UUID Marker in bulk messages and attributes

Send larger volumes

bulk.mjs logs a fixed number of small records. Each has a runId and an increasing sequence attribute.

# Default: 10,000 records at about 1,000 per second.
npm run bulk

# 100,000 records at about 5,000 per second in batches of 500, with a known run ID.
export RUN_ID="bulk-$(date +%s)"
LOG_COUNT=100000 LOG_RATE=5000 BATCH_SIZE=500 npm run bulk

It prints a JSON summary with the runId and the number of records produced. That counts logger calls, not records Logbrook stored. Ctrl-C or SIGTERM stops production, then drains the transport as usual.

To see what arrived, count by the run ID:

export RUN_ID='<runId printed by npm run bulk>'

logbrook count "$LOGBROOK_INDEX" --since 1h --message "bulk example run=$RUN_ID"

If nothing was dropped, expired or sent twice, the count equals the number you produced. A higher count means retries stored duplicates or the run ID was reused. For a lower count, check the transport’s stderr, the server logs and the index’s retention.

Choose a batch size

BATCH_SIZE counts records. The transport also splits batches at its maxBatchBytes limit, 1 MiB by default, and doesn’t compress requests. The server’s default limits are 1,000 events and 1 MiB per request.

Start with 250 records per batch and try 500 or 1,000 if your records are small. For a quiet service, lower BATCH_INTERVAL_MS if a second is too long to wait for a partial batch.

The transport doesn’t check the server’s event, field or nesting limits. One invalid or oversized event rejects its whole batch, and retrying won’t fix it. If your server has a smaller body limit, set maxBatchBytes in logger.mjs to match.

Delivery and shutdown

The transport worker sends one HTTP request at a time and keeps records in order. There is no concurrency option.

Queue overflow. MAX_BUFFER_SIZE caps the number of waiting records, and the transport’s maxBufferBytes caps their serialized size at 64 MiB by default. When either cap is reached, the transport drops the oldest waiting records and warns on stderr. It doesn’t slow your application down.

Retries. pino-http-transport 2.1.0 retries network errors, timeouts and every non-2xx response, including permanent ones such as 401 and 413. It ignores Retry-After and adds no jitter. When a batch runs out of retries, the transport reports the error, discards the batch and moves on, and close() then fails.

Draining on shutdown. close() flushes the transport, waits for it to deliver everything, including partial batches and retries, then ends the worker. A delivery error makes close() fail, and the worker is ended anyway. Flushing first matters because Pino’s worker end() blocks the main thread for up to about 10 seconds. The flush has no overall deadline; each HTTP attempt still uses HTTP_TIMEOUT_MS.

In a service:

  1. Stop accepting new work.
  2. Wait for in-flight requests to finish and stop producing logs.
  3. Call close() and watch stderr for delivery errors.

Give the process manager enough shutdown time, or it will kill the process before delivery finishes.

Troubleshooting

Transport messages go to stderr with a [pino-http-transport] prefix.

Error Likely cause What to do
HTTP 401 Missing or wrong token, or a read or admin token Use the server’s ingestion token
HTTP 403 The token’s index scope excludes this index Use an allowed index or update the token’s index scopes
HTTP 400 No msg, a non-numeric level or time, or a time outside the retention window or more than five minutes ahead Keep Pino’s default formats and check the host clock
HTTP 413 Too many events, or a request, event or field over the limits Lower BATCH_SIZE or trim large fields
HTTP 429 The server is at capacity, or creating the index would exceed its index limit Reduce the rate or add capacity. Check logbrook indexes list.
HTTP 507 The index reached its disk-size target Review the index’s retention and size settings
HTTP request timed out The server took longer than HTTP_TIMEOUT_MS Check server load before raising the timeout
Buffer limit exceeded The queue was full and the oldest records were dropped Lower the log rate or send larger batches

Next steps

Type to search…

↑↓ navigate↵ selectEsc close