or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

child-loggers-serializers.mdcli-tools.mdcore-logging.mdindex.mdstream-management.md
tile.json

tessl/npm-bunyan

A JSON logging library for Node.js services with structured logging and CLI tools

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/bunyan@2.0.x

To install, run

npx @tessl/cli install tessl/npm-bunyan@2.0.0

index.mddocs/

Bunyan

Bunyan is a simple and fast JSON logging library for Node.js services that provides structured logging with both a programmatic API and a command-line tool for viewing logs. It supports multiple output streams, custom serializers, child loggers for request tracking, and advanced features like log rotation and DTrace integration.

Package Information

  • Package Name: bunyan
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install bunyan

Core Imports

const bunyan = require('bunyan');
const log = bunyan.createLogger({name: 'myapp'});

ES6 import (via bundlers):

import bunyan from 'bunyan';
import { createLogger, TRACE, DEBUG, INFO, WARN, ERROR, FATAL } from 'bunyan';

Basic Usage

const bunyan = require('bunyan');

// Create a logger
const log = bunyan.createLogger({name: 'myapp'});

// Log messages at different levels
log.info('Application started');
log.warn('This is a warning');
log.error('An error occurred');

// Log with structured data
log.info({user: 'alice', action: 'login'}, 'User login attempt');

// Create child logger with additional context
const reqLog = log.child({req_id: '12345'});
reqLog.info('Processing request');

// Using standard serializers for HTTP objects and errors
const webLog = bunyan.createLogger({
  name: 'webapp',
  serializers: bunyan.stdSerializers
});

try {
  // This would log HTTP request/response objects safely
  webLog.info({req: request, res: response}, 'HTTP request processed');
} catch (err) {
  // This safely serializes error objects with stack traces
  webLog.error({err: err}, 'Request processing failed');
}

Architecture

Bunyan is built around several key components:

  • Logger Class: Core logging functionality with configurable levels and output streams
  • Stream System: Flexible output routing to files, stdout, or custom streams with individual level controls
  • Serializers: Pluggable functions for converting objects (errors, HTTP requests/responses) to JSON
  • Child Loggers: Context-aware logger instances that inherit parent configuration while adding specific fields
  • CLI Tool: Command-line utility for viewing, filtering, and formatting JSON log files
  • Optional Features: DTrace integration, log rotation, and browser compatibility

Capabilities

Core Logging

Primary logging functionality with configurable levels, structured data support, and printf-style formatting.

function createLogger(options: LoggerOptions): Logger;

interface LoggerOptions {
  name: string;                    // Required logger name
  level?: string | number;         // Minimum log level (default: INFO)
  stream?: NodeJS.WritableStream;  // Single output stream
  streams?: StreamConfig[];        // Multiple streams with different levels
  serializers?: Serializers;      // Custom field serializers
  src?: boolean;                   // Include source location info
  hostname?: string;               // Override hostname in logs
}

Core Logging

Stream Management

Configure and manage multiple output streams with individual log levels, file outputs, and log rotation.

interface StreamConfig {
  type?: 'stream' | 'file' | 'rotating-file' | 'raw';
  level?: string | number;
  stream?: NodeJS.WritableStream;
  path?: string;
  period?: string;    // For rotating files: '1d', '1h', etc.
  count?: number;     // Number of rotated files to keep
}

class Logger {
  addStream(stream: StreamConfig, defaultLevel?: string | number): void;
  reopenFileStreams(): void;
  close(): void;
}

Stream Management

Child Loggers and Serializers

Create specialized logger instances with additional context and configure custom serialization for complex objects.

class Logger {
  child(options: ChildOptions, simple?: boolean): Logger;
  addSerializers(serializers: Serializers): void;
}

interface ChildOptions {
  [key: string]: any;  // Additional fields for child logger
  level?: string | number;
  serializers?: Serializers;
}

interface Serializers {
  [fieldName: string]: (obj: any) => any;
}

Child Loggers and Serializers

CLI Tools

Command-line utility for viewing, filtering, and formatting bunyan JSON log files with human-readable output.

bunyan [OPTIONS] [FILE ...]

# Common options:
# -o, --output FORMAT     Output format: long, short, simple, json, bunyan
# -l, --level LEVEL       Filter by minimum log level
# -c, --condition COND    Boolean filter condition
# --time start-end        Filter by time range
# --pid PID               Filter by process ID

CLI Tools

Log Levels

Bunyan defines six log levels with corresponding numeric values:

  • FATAL (60): The service/app is going to stop or become unusable
  • ERROR (50): Fatal for a particular request, but the service continues
  • WARN (40): A note on something that should probably be looked at
  • INFO (30): General operational messages about what's happening
  • DEBUG (20): Anything else, detailed information for debugging
  • TRACE (10): Logging from external libraries used by your app

Types

// Log level constants
const TRACE: 10;
const DEBUG: 20;
const INFO: 30;
const WARN: 40;
const ERROR: 50;
const FATAL: 60;

// Standard serializers for common objects
const stdSerializers: {
  req: (req: any) => any;    // HTTP request serializer
  res: (res: any) => any;    // HTTP response serializer
  err: (err: Error) => any;  // Error object serializer
};

// Utility classes
class RingBuffer {
  constructor(options: {limit?: number});
  limit: number;
  records: any[];
}

class RotatingFileStream {
  constructor(options: RotatingFileOptions);
  write(data: string): void;
  rotate(): void;
}

interface RotatingFileOptions {
  path: string;
  period?: string;
  count?: number;
}

// Utility functions
function resolveLevel(nameOrNum: string | number): number;
function levelFromName(name: string): number;
function nameFromLevel(level: number): string;
function safeCycles(): (key: string, value: any) => any;