Open Source Package

@smooai/logger

Contextual logging for AWS Lambda and browser environments. Two implementations: AwsServerLogger for Lambda with CloudWatch-formatted JSON output, and BrowserLogger for frontend with styled console output.

Overview

Traditional loggers give you the message but not the story. @smooai/logger automatically captures the full execution context you need to debug production issues, without the manual setup. It provides two purpose-built implementations for server and client environments.

AwsServerLogger

For Lambda, ECS, and Fargate. Outputs CloudWatch-formatted JSON with automatic request ID extraction, correlation tracking, and full call stack context.

BrowserLogger

For frontend applications. Styled console output with device detection, browser context, and correlation ID propagation across API calls.

Features

Correlation ID Tracking

Automatically flow correlation IDs across services via HTTP headers, SQS attributes, and EventBridge events.

Automatic Lambda Context

Extracts requestId, function name, memory allocation, and other metadata from Lambda execution context automatically.

Six Log Levels

Full support for TRACE, DEBUG, INFO, WARN, ERROR, and FATAL levels with configurable minimum thresholds.

TypeScript-First API

Full type safety with typed context objects, structured metadata, and IntelliSense-friendly configuration.

Installation

pnpm add @smooai/logger

Quick Start

Get structured, contextual logging in just a few lines of code.

import { AwsServerLogger } from '@smooai/logger';

const logger = new AwsServerLogger({
    service: 'user-api',
    environment: 'production',
});

logger.info('Processing request', { userId: '123', action: 'update' });
logger.error('Database connection failed', { retryCount: 3 });

AWS Server Logger

The AwsServerLogger is designed for AWS Lambda, ECS, Fargate, and EC2 environments. It outputs structured JSON formatted for CloudWatch and automatically captures execution context.

import { AwsServerLogger } from '@smooai/logger/AwsServerLogger';

const logger = new AwsServerLogger({ name: 'UserAPI' });

export const handler = async (event, context) => {
    // Automatically extracts requestId, function name, memory, etc.
    logger.addLambdaContext(event, context);

    try {
        const user = await createUser(event.body);
        logger.info('User created successfully', { userId: user.id });
        return { statusCode: 201, body: JSON.stringify(user) };
    } catch (error) {
        logger.error('Failed to create user', error, {
            body: event.body,
            headers: event.headers,
        });
        throw error;
    }
};

Every log entry includes the exact code location (file, line number, and call stack) so you never have to guess which function logged what.

Browser Logger

The BrowserLogger provides styled console output with automatic device detection, browser context, and correlation ID propagation across API calls.

import { BrowserLogger } from '@smooai/logger/browser/BrowserLogger';

const logger = new BrowserLogger({ name: 'CheckoutFlow' });

// Automatically captures browser context
const response = await fetch('/api/checkout', {
    method: 'POST',
    headers: { 'X-Correlation-Id': logger.correlationId() },
});

logger.addResponseContext(response);
logger.info('Checkout completed', { orderId: data.id });

// Output includes: browser name/version, platform, device type,
// HTTP request/response details, and correlation IDs

Log Levels

Six log levels from most to least verbose. Set the minimum level to control output verbosity.

LevelDescription
TRACEDetailed debugging information for tracing code execution
DEBUGDiagnostic information useful during development
INFOGeneral operational information about normal application flow
WARNWarning conditions that may require attention
ERRORError conditions that need investigation
FATALCritical failures that require immediate action

Correlation IDs

Correlation IDs automatically flow through your entire system, linking logs across services so you can trace a single request from API Gateway through Lambda, SQS, and back.

// Service A: API Gateway Handler
logger.addLambdaContext(event, context);
logger.info('Request received'); // Correlation ID: abc-123

// Service B: SQS Processor (automatically extracts ID from message attributes)
logger.addSQSRecordContext(record);
logger.info('Processing message'); // Same Correlation ID: abc-123

// Service C: Another Lambda (receives via HTTP header)
logger.info('Completing workflow'); // Still Correlation ID: abc-123

Context Management

Add persistent context that is included in every subsequent log entry, or pass one-off context to individual log calls.

// Add user context that persists across logs
logger.addUserContext({ id: 'user-123', role: 'admin' });

// Add telemetry for performance tracking
logger.addTelemetryFields({ duration: 150, operation: 'db-query' });

// Add custom context for a specific log entry
logger.info('Payment processed', {
    amount: 99.99,
    currency: 'USD',
});

Real-World Example: SQS Processing

A complete example showing how the logger captures context across an SQS message processing workflow.

import { AwsServerLogger } from '@smooai/logger/AwsServerLogger';

const logger = new AwsServerLogger({ name: 'OrderProcessor' });

export const sqsHandler = async (event) => {
    for (const record of event.Records) {
        // Automatically extracts correlation ID, message attributes, and queue info
        logger.addSQSRecordContext(record);
        logger.info('Processing order', {
            messageId: record.messageId,
            attempt: record.attributes.ApproximateReceiveCount,
        });

        await processOrder(record.body);
        logger.info('Order processed successfully');
    }
};

Configuration

Customize logger behavior with these options.

OptionDescription
nameLogger name, included in every log entry for identification
levelMinimum log level (TRACE, DEBUG, INFO, WARN, ERROR, FATAL). Defaults to INFO.
prettyPrintEnable human-readable console output for local development. Auto-enabled when SST_DEV is set.
contextPresetMINIMAL for essential context only, or FULL for all available context (default).