Skip to content
Logixlysia
Esc
↑↓navigate↵open⌘Jpreview
On this page

Custom Transports

Send logs to external services

Send logs to external services using custom transports. Transports work alongside built-in console and file logging.

Looking for Axiom, Better Stack, ClickHouse, Datadog, HyperDX, Loki, OTLP, PostHog, or Sentry? Built-in adapters cover those — with batching, retries, and credential handling included. Custom transports are for everything else.

Output Behavior

Logixlysia supports three types of logging outputs:

  1. Console Logging - Built-in console output
  2. File Logging - Built-in file output
  3. Transport Logging - Custom external services

Controlling Outputs

  • Default: Console + File (if logFilePath is set) + Transports
  • disableInternalLogger: true: Disables console logging only
  • disableFileLogging: true: Disables file logging only
  • useTransportsOnly: true: Disables both console and file, uses only transports

Basic Transport

type Transport = {
  log: (
    level: LogLevel,
    message: string,
    meta?: Record<string, unknown>
  ) => void | Promise<void>
  flush?: (options?: { signal?: AbortSignal }) => void | Promise<void>
  close?: (options?: { signal?: AbortSignal }) => void | Promise<void>
  minLevel?: LogLevel
}

const consoleTransport: Transport = {
  log: (level, message, meta) => {
    console.log(`[${level}] ${message}`, meta)
  }
}

app.use(
  logixlysia({
    config: {
      transports: [consoleTransport]
    }
  })
)

log is the only required member. An entry without a log function makes the plugin throw logixlysia: invalid output config when you construct it, naming the entry by index (for example transports[0].log must be a function). Implement flush when your transport batches or queues entries — the plugin calls it on shutdown so the last lines before an exit still arrive, and after each request and runJob job when you set waitUntil. Implement close when you hold a socket, timer, or buffer that must be released; it is never called automatically, only through flushLogixlysia(options, { close: true }), and it must be idempotent. When the call has a deadline (the stop hook’s flushTimeoutMs, the per-request flush handed to waitUntil, or flushLogixlysia with timeoutMs), flush and close receive { signal }, which aborts at the deadline; read it to give up early, or ignore it, since the plugin stops waiting at the deadline either way. Without a deadline they are called with no argument.

meta always carries request.method, request.url and durationMs, plus the merged context when there is one. It carries service when service is set. An access line adds status, and its message argument is the empty string. An error line adds status, message and error, a plain object with message, name, status, code, why, fix, link and internal when the error carried them, plus stack unless the error’s own status is below 500. A thrown plain object arrives with its own fields plus message; a thrown string or number arrives as { message, value }. The check reads the error object, not the response status, so a plain Error that your onError maps to a 400 still carries a stack.

External Services

Elasticsearch

createHttpTransport from logixlysia/http is the batching, retrying core that the built-in adapters share, so a backend that takes an HTTP POST gets batching, retry with backoff, a bounded queue, onDropped, flush and close by describing only its request body. A log you write yourself gets none of that.

import { createHttpTransport, entryText } from 'logixlysia/http'

const elasticsearchTransport = createHttpTransport({
  name: 'elasticsearch',
  url: 'http://elasticsearch:9200/logs/_bulk',
  headers: { 'Content-Type': 'application/x-ndjson' },
  options: { maxBatchSize: 100, onError: console.error },
  rejected: response => {
    const { items = [] } = response as {
      items?: { index?: { error?: unknown } }[]
    }
    return { count: items.filter(item => item.index?.error).length }
  },
  body: entries =>
    entries
      .map(entry =>
        [
          JSON.stringify({ index: {} }),
          JSON.stringify({
            ...entry.meta,
            level: entry.level,
            message: entryText(entry),
            '@timestamp': entry.timestamp.toISOString()
          })
        ].join('\n')
      )
      .join('\n') + '\n'
})

Elasticsearch answers 200 when single documents in a _bulk request failed, so the example adds a rejected hook. It receives the parsed JSON body of a successful response and returns how many entries the backend did not store. Those entries reach onDropped with the reason 'rejected' and are not retried. A response body that is not JSON, or is larger than 1 MiB, is not parsed, and nothing is counted from it.

MongoDB

const mongodbTransport = {
  log: async (level, message, meta) => {
    try {
      await db.collection('logs').insertOne({
        level,
        message,
        ...meta,
        timestamp: new Date()
      })
    } catch (err) {
      console.error('MongoDB transport error', err)
    }
  }
}

Slack

const slackTransport = {
  log: async (level, message, meta) => {
    if (level.toLowerCase() === 'error') {
      const webhook = process.env.SLACK_WEBHOOK_URL
      if (!webhook) return

      try {
        await fetch(webhook, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            text: `[${level}] ${message}\n${JSON.stringify(meta, null, 2)}`
          })
        })
      } catch (err) {
        console.error('Slack transport error', err)
      }
    }
  }
}

Multiple Transports

app.use(
  logixlysia({
    config: {
      transports: [elasticsearchTransport, slackTransport]
    }
  })
)

Minimum Level

Set minLevel on a transport to send it only records at that level or louder. The levels, quietest first, are DEBUG, INFO, WARNING and ERROR. Records below it skip the transport and are not counted as dropped. A transport without minLevel receives every level. Any other value, such as 'error' or 'WARN', makes the plugin throw logixlysia: invalid output config when you construct it.

import { Elysia } from 'elysia'
import logixlysia from 'logixlysia'
import { createAxiomTransport } from 'logixlysia/axiom'
import { createSentryTransport } from 'logixlysia/sentry'

const app = new Elysia().use(
  logixlysia({
    config: {
      transports: [
        createSentryTransport({ minLevel: 'ERROR' }),
        createAxiomTransport()
      ]
    }
  })
)

A transport you write yourself takes the same field, and withRedaction keeps the one on the transport it wraps.

Transport-Only Logging

app.use(
  logixlysia({
    config: {
      useTransportsOnly: true,
      transports: [elasticsearchTransport, slackTransport]
    }
  })
)

Testing Your Logs

logixlysia/testing has a memory transport that keeps typed records for assertions. See Testing Your Logs.

Best Practices

  • Handle transport errors gracefully
  • Implement retry logic for critical transports
  • Use async transports for better performance
  • Secure transport credentials
  • Avoid logging secrets or PII
  • Use useTransportsOnly for production environments where you only want external logging

Was this page helpful?