Logging Subsystem

Katal includes a high-performance, asynchronous logging subsystem designed for high-concurrency production runtimes. It supports multiple concurrent destinations (Console, File, Streams), colored development output, structured JSON logging, and automatic error serialization.


1. Quick Start

import { LoggingIntegration, LogLevel } from "katal/logging";

// 1. Initialize logger with multiple destinations
const logger = new LoggingIntegration()
    .setMinLevel(LogLevel.INFO)
    .toConsole()
    .toFile("./logs/application.log");

// 2. Structured logging with contextual metadata
await logger.info("Server booted successfully", {
    port: 3000,
    environment: "production",
});

// 3. Error logging with automatic stack trace extraction
try {
    throw new Error("Database connection timed out");
} catch (error: any) {
    await logger.error("Failed to execute query", error, {
        query: "SELECT * FROM orders WHERE id = $1",
        timeoutMs: 5000,
    });
}

2. Log Levels & Filtering

Logs below the configured minLevel threshold are dropped immediately with near-zero overhead:

export enum LogLevel {
    DEBUG = "debug",
    INFO  = "info",
    WARN  = "warn",
    ERROR = "error",
}

// Only log warnings and errors in production
const logger = new LoggingIntegration()
    .setMinLevel(process.env.NODE_ENV === "production" ? LogLevel.WARN : LogLevel.DEBUG)
    .toConsole();

3. Built-in Destinations

A. Colored Console Destination

Formats log entries with human-readable timestamps, level-based ANSI colors, and pretty-printed context objects during local development:

const logger = new LoggingIntegration()
    .toConsole();

// Development terminal output:
// [2026-10-14T23:45:00.123Z] INFO  Application listening on port 3000
// [2026-10-14T23:45:01.456Z] WARN  High memory consumption detected { heapMb: 850 }
// [2026-10-14T23:45:02.789Z] ERROR Payment gateway unreachable Error: ECONNRESET

B. Atomic File Destination

Appends logs to disk with atomic operations and automatic parent directory creation:

const logger = new LoggingIntegration()
    .toFile("./logs/app.log")
    .toFile("./logs/errors.log", { minLevel: LogLevel.ERROR });

4. Custom Destinations (OpenTelemetry, Sentry, Datadog)

Implement the LogDestination contract to route logs to your centralized telemetry platforms:

import type { LogDestination, LogEntry } from "katal/logging";

// Example Datadog / HTTP Stream Destination
export class DatadogDestination implements LogDestination {
    constructor(private readonly apiKey: string) {}

    async write(entry: LogEntry): Promise<void> {
        const payload = {
            ddsource: "katal",
            service: "api-backend",
            status: entry.level,
            message: entry.message,
            timestamp: entry.timestamp.toISOString(),
            context: entry.context,
            error: entry.error ? {
                message: entry.error.message,
                stack: entry.error.stack,
            } : undefined,
        };

        await fetch("https://http-intake.logs.datadoghq.com/api/v2/logs", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "DD-API-KEY": this.apiKey,
            },
            body: JSON.stringify(payload),
        });
    }
}

// Attach custom destination
logger.addDestination(new DatadogDestination(process.env.DD_API_KEY!));

5. Integrating with Application Request Context

Inject the logger into controllers or services via the IoC container:

import { Controller } from "katal";
import type { RequestContext } from "katal";
import { LoggingIntegration } from "katal/logging";

export class OrderCheckoutController extends Controller {
    constructor(private readonly logger: LoggingIntegration) {
        super();
    }

    async handle(ctx: RequestContext) {
        await this.logger.info("Processing checkout", {
            requestId: ctx.id,
            userId: ctx.user?.id,
            path: ctx.url.pathname,
        });

        // Checkout logic...
        return this.created({ status: "processed" });
    }
}

6. Error Safety

Katal's logging pipeline protects against cascading application failures. If a disk write or remote HTTP telemetry destination fails, the exception is isolated and will never crash your active HTTP requests.


See Also