npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

serverless-event-logger

v1.0.1

Published

🚀 Lightweight, zero-dependency structured JSON logger for AWS Lambda. Optimized for observability with automatic context extraction from serverless events.

Readme

serverless-event-logger

🚀 Lightweight, zero-dependency structured JSON logger for AWS Lambda. Optimized for observability with automatic context extraction from serverless events.

npm version License: MIT

Features

  • Zero dependencies - Minimal bundle size (< 5KB minified)
  • Structured JSON output - Perfect for CloudWatch Insights queries
  • Automatic context extraction - Captures requestId, userId, segment from events
  • Log level filtering - debug, info, warn, error
  • Sensitive data redaction - Automatically redact passwords, tokens, etc.
  • Timer utility - Measure operation duration
  • Child loggers - Add module-specific context
  • TypeScript first - Full type definitions included

Installation

npm install serverless-event-logger

Quick Start

import { createLogger } from 'serverless-event-logger';

// Create a logger instance
const logger = createLogger({
  service: 'my-lambda',
});

// Basic logging
logger.info('User created', { userId: '123' });
// Output: {"timestamp":"2024-01-15T10:30:00.000Z","level":"info","message":"User created","service":"my-lambda","userId":"123"}

logger.error('Database connection failed', { error: err.message });

Usage with Lambda Events

import { createLogger } from 'serverless-event-logger';
import { NormalizedEvent } from 'serverless-event-orchestrator';

const logger = createLogger({
  service: 'ml-properties-lambda',
});

async function handler(event: NormalizedEvent) {
  // Create logger with request context
  const log = logger.withContext(event);
  
  log.info('Handler started');
  // Output includes: requestId, userId, segment, path, method
  
  try {
    const result = await processRequest(event);
    log.info('Request processed', { resultId: result.id });
    return result;
  } catch (error) {
    log.error('Request failed', { error: error.message, stack: error.stack });
    throw error;
  }
}

API Reference

createLogger(config)

Creates a new logger instance.

interface LoggerConfig {
  service: string;                    // REQUIRED: Name of your lambda/service
  defaultLevel?: LogLevel;            // Default: 'info'
  silent?: boolean;                   // Default: false (set true for tests)
  redactPaths?: string[];             // Fields to redact (e.g., ['password', 'token'])
  timestampFormat?: 'iso' | 'epoch';  // Default: 'iso'
  pretty?: boolean;                   // Default: false (formatted output for local dev)
}

type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';

Logging Methods

logger.debug(message: string, data?: object): void
logger.info(message: string, data?: object): void
logger.warn(message: string, data?: object): void
logger.error(message: string, data?: object): void

logger.withContext(event)

Creates a new logger with context extracted from a NormalizedEvent:

const log = logger.withContext(event);
// Extracts: requestId, userId, segment, path, method, userAgent

logger.child(fields)

Creates a child logger with additional fixed fields:

const dbLogger = logger.child({ module: 'dynamodb' });
dbLogger.info('Query executed', { table: 'Users' });
// Output includes module: 'dynamodb'

logger.startTimer(label)

Measures operation duration:

const timer = log.startTimer('database-query');
await db.query(...);
timer.done({ recordsFound: 150 });
// Output: {"message":"database-query completed","duration":234,"recordsFound":150,...}

Configuration

Environment Variables

| Variable | Description | Default | |----------|-------------|---------| | LOG_LEVEL | Minimum log level | info | | LOG_SILENT | Disable all logs | false | | LOG_PRETTY | Formatted output | false |

Sensitive Data Redaction

const logger = createLogger({
  service: 'auth-lambda',
  redactPaths: ['password', 'token', 'authorization', 'apiKey'],
});

logger.info('Login attempt', { 
  username: 'john',
  password: 'secret123' 
});
// Output: {..., "username": "john", "password": "[REDACTED]"}

Log Output Structure

Base Fields (always present)

{
  "timestamp": "2024-01-15T10:30:00.000Z",
  "level": "info",
  "message": "Your log message",
  "service": "your-service-name"
}

Context Fields (with withContext)

{
  "requestId": "abc-123-def-456",
  "userId": "user_abc123",
  "segment": "private",
  "path": "/api/users",
  "method": "POST",
  "userAgent": "Mozilla/5.0..."
}

CloudWatch Insights Queries

Find errors by endpoint

fields @timestamp, message, path, method, error, userId
| filter level = "error"
| filter service = "my-lambda"
| sort @timestamp desc
| limit 100

Latency analysis

fields @timestamp, path, method, duration
| filter message like /completed/
| stats avg(duration) as avg_ms, max(duration) as max_ms by path, method
| sort avg_ms desc

User activity trace

fields @timestamp, level, message, path
| filter userId = "user_abc123"
| sort @timestamp desc
| limit 50

TypeScript Support

Full TypeScript definitions are included:

import { 
  createLogger, 
  Logger, 
  LoggerConfig, 
  LogLevel,
  Timer,
  NormalizedEventLike 
} from 'serverless-event-logger';

Best Practices

  1. Create one logger per service - Initialize at module level
  2. Use withContext in handlers - Captures request-specific info
  3. Use child for modules - Adds component context
  4. Redact sensitive data - Configure redactPaths
  5. Use timers for slow operations - Helps identify bottlenecks
// src/logging.ts
export const logger = createLogger({
  service: process.env.LAMBDA_NAME || 'unknown-lambda',
  redactPaths: ['password', 'token', 'authorization'],
});

// src/handlers/user.ts
import { logger } from '../logging';

export async function createUser(event: NormalizedEvent) {
  const log = logger.withContext(event);
  log.info('Creating user', { email: event.payload.body.email });
  // ...
}

// src/repositories/user-repository.ts
import { logger } from '../logging';

const log = logger.child({ module: 'UserRepository' });

export async function save(user: User) {
  const timer = log.startTimer('dynamodb-put');
  await db.put(user);
  timer.done({ userId: user.id });
}

License

MIT © MLHolding