Skip to content

LogLayerUnifies Logging

A layer on top of Javascript logging libraries to provide a consistent logging experience.

LogLayer logo by Akshaya Madhavan

javascript
// Example using the Pino logging library with LogLayer
// You can also start out with a console logger and swap to another later!
import { LogLayer } from 'loglayer';
import { pino } from 'pino';
import { PinoTransport } from '@loglayer/transport-pino';
import { redactionPlugin } from '@loglayer/plugin-redaction';

const log = new LogLayer({
  // Multiple loggers can also be used at the same time. 
  transport: new PinoTransport({
    logger: pino()
  }),
  // Plugins modify log data before it's shipped to your logging library.
  plugins: [
    redactionPlugin({
      paths: ['password'],
      censor: '[REDACTED]',
    }),
  ],
  // Put context data in a specific field (default is flattened)
  contextFieldName: 'context',
  // Put metadata in a specific field (default is flattened)
  metadataFieldName: 'metadata',
})

// persisted data that is always included in logs
log.withContext({
  path: "/",
  reqId: "1234"
})

log.withPrefix("[my-app]")
  .withError(new Error('test'))
  // data that is included for this log entry only
  .withMetadata({ some: 'data', password: 'my-pass' })
  // Non-object data only (numbers and strings only)
  // this can be omitted to just log an object / error
  // by using .errorOnly() / .metadataOnly() instead of withError() / withMetadata()
  .info('my message')
json5
{
  "level": 30,
  "time": 1735857465669,
  "msg": "[my-app] my message",
  "context": {
    "path": "/",
    "reqId": "1234",
  },
  "metadata": {
    "password": "[REDACTED]",
    "some": "data",    
  },
  "err":{
    "type": "Error",
    "message": "test",
    "stack": "Error: test\n ..."
  }
}

Use the Pretty Terminal Transport to view logs in the terminal with filtering and detailed viewing capabilities.

Add Wide Event Logging with Mixins

Capture rich, self-contained log entries that span async boundaries. Use the Wide Events Mixin to accumulate data across your request:

typescript
import { LogLayer, useLogLayerMixin, ConsoleTransport } from 'loglayer';
import { AsyncLocalStorage } from 'async_hooks';
import { createWideEventMixin } from '@loglayer/mixin-wide-events';

// Set up async context for propagating wide event data
const asyncLocalStorage = new AsyncLocalStorage<Record<string, any>>();

// Register the mixin (called before creating instances)
useLogLayerMixin(createWideEventMixin({ asyncContext: asyncLocalStorage }));

// Create LogLayer instance
const log = new LogLayer({
  transport: new ConsoleTransport({
    logger: console
  })
});

// Accumulate data across async boundaries
asyncLocalStorage.run({}, () => {
  log.withWideEvents({ userId: '123', ip: '10.0.0.1' });
  log.info('User logged in');

  log.withWideEvents({ action: 'view' });
  log.info('User performed action');

  // Emit the accumulated wide event as a single log entry
  log.emitWideEvent({ message: 'Request completed' });
});

Built-in Transports

NameDescription
Console Browser Server Deno BunSimple console-based logging for development
Structured Browser Server Deno BunConsole-based structured logging with level, time, and msg fields enabled by default
Blank Transport Browser Server Deno BunFor quickly creating / prototyping new transports

Logging Libraries

NamePackageChangelogDescription
Bunyan Browser ServernpmChangelogJSON logging library for Node.js
Consola ServernpmChangelogElegant console logger for Node.js and browser
Electron-log ServernpmChangelogLogging library for Electron applications
Log4js ServernpmChangelogPort of Log4j framework to Node.js
loglevel Browser ServernpmChangelogMinimal lightweight logging for JavaScript
LogTape Browser Server Deno BunnpmChangelogModern, structured logging library for TypeScript and JavaScript
Pino Browser ServernpmChangelogVery low overhead Node.js logger
Roarr Browser ServernpmChangelogJSON logger for Node.js and browser
Signale ServernpmChangelogHighly configurable CLI logger
tslog Browser Server Deno BunnpmChangelogPowerful, fast and expressive logging for TypeScript and JavaScript
Tracer ServernpmChangelogTracer logging library for Node.js
Winston Browser ServernpmChangelogA logger for just about everything

Cloud Providers

NamePackageChangelogDescription
Amazon CloudWatch Logs ServernpmChangelogLogging for Amazon CloudWatch Logs
AWS Lambda Powertools Logger ServernpmChangelogLogging for AWS Lambdas
Axiom ServernpmChangelogSend logs to Axiom cloud logging platform
Better Stack Server Deno BunnpmChangelogSend logs to Better Stack log management platform
Cribl HTTP/S Browser Server Deno BunnpmChangelogSend logs to Cribl Stream via HTTP/S Bulk API source
Datadog ServernpmChangelogServer-side logging for Datadog
Datadog Browser Logs BrowsernpmChangelogBrowser-side logging for Datadog
Dynatrace ServernpmChangelogServer-side logging for Dynatrace
Google Cloud Logging ServernpmChangelogServer-side logging for Google Cloud Platform
New Relic Server Deno BunnpmChangelogServer-side logging for New Relic
Sentry Browser Server Deno BunnpmChangelogSend structured logs to Sentry using the Sentry SDK logger API
Logflare Server Deno BunnpmChangelogSend logs to Logflare log ingestion and querying engine
Sumo Logic ServernpmChangelogSend logs to Sumo Logic via HTTP Source
VictoriaLogs Server Deno BunnpmChangelogSend logs to VictoriaLogs by Victoria Metrics using JSON stream API

Other Transports

NamePackageChangelogDescription
HTTP Browser Server Deno BunnpmChangelogGeneric HTTP transport with batching, compression, and retry support
Log File Rotation ServernpmChangelogWrite logs to local files with rotation support
OpenTelemetry ServernpmChangelogSend logs using the OpenTelemetry Logs SDK
Pretty Terminal Server BunnpmChangelogPretty prints logs in the terminal with text search / advanced interactivity.
Simple Pretty Terminal Browser Server Deno BunnpmChangelogPretty prints logs in the browser / terminal / Next.js.

Available Plugins

NamePackageChangelogDescription
Datadog APM Trace Injector ServernpmChangelogAutomatically inject Datadog APM trace context into logs for correlation
Filter Browser ServernpmChangelogFilter logs using string patterns, regular expressions, or JSON Queries
OpenTelemetry ServernpmChangelogAdd OpenTelemetry trace context to logs
Redaction Browser ServernpmChangelogRedact sensitive information from logs
Sprintf Browser ServernpmChangelogPrintf-style string formatting support
Sampling Browser Server Deno BunnpmChangelogRandomly drop log entries to control volume with rate-based or per-level strategies

Available Integrations

NamePackageChangelogDescription
ElysiaJS Server BunnpmChangelogRequest-scoped logging for ElysiaJS with auto request/response logging
Express Server Bun DenonpmChangelogRequest-scoped logging for Express with auto request/response logging
Fastify ServernpmChangelogRequest-scoped logging for Fastify with auto request/response logging
Hono Server Bun DenonpmChangelogRequest-scoped logging for Hono with auto request/response logging
Koa ServernpmChangelogRequest-scoped logging for Koa with auto request/response logging

Available Mixins

NamePackageDescription
Wide Events Browser Server Deno BunnpmAdds wide event logging for comprehensive, self-contained log entries
Datadog Metrics (HTTP) ServernpmAdds the datadog-metrics API to LogLayer
Hot-Shots (StatsD) ServernpmAdds the hot-shots API to LogLayer

LogLayer is made with ❤️ by Theo Gravity / Disaresta. Logo by Akshaya Madhavan.