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

@megallm/logger

v1.0.2

Published

Enterprise-grade logging package with Loki, OpenTelemetry, file rotation, and beautiful console output

Readme

mega-logger

Enterprise-grade logging for Node.js with beautiful console output, Loki integration, OpenTelemetry support, and daily file rotation.

Features

  • Beautiful Console Output - Colorful, emoji-rich logs in development; structured JSON in production
  • Multiple Log Levels - trace, debug, info, success, warn, error, fatal, silent
  • Daily File Rotation - Automatic log file rotation with size limits and compression
  • Loki Integration - Send logs to Grafana Loki for aggregation and querying
  • OpenTelemetry Support - Distributed tracing with automatic span correlation
  • Child Loggers - Create contextual loggers with inherited metadata
  • Performance Timing - Built-in utilities for measuring operation duration
  • TypeScript-First - Full type safety with comprehensive type exports
  • Zero Config - Works out of the box with sensible defaults

Installation

npm install mega-logger

For OpenTelemetry support (optional):

npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-http

Quick Start

import { logger } from 'mega-logger';

// Simple logging
logger.info('Application started');
logger.debug('Debug information', { userId: 123 });
logger.error('Something went wrong', new Error('Failed to connect'));

// With timing
await logger.withTiming('database query', async () => {
  // Your operation here
});

Configuration

Basic Configuration

import { Logger } from 'mega-logger';

const logger = new Logger({
  level: 'debug',
  service: 'my-app',
  environment: 'development',
  defaultMetadata: {
    version: '1.0.0',
  },
});

Environment Variables

  • LOG_LEVEL - Set minimum log level (trace, debug, info, warn, error, fatal, silent)
  • NODE_ENV - Set environment (development, production, test)
  • SERVICE_NAME - Set service name for logs

Console Output

Development mode shows beautiful, colorful logs:

[10:30:45.123] ℹ️  INFO    [my-app] User logged in
  userId: 123
  email: "[email protected]"

Production mode outputs structured JSON:

{
  "timestamp": "2024-01-15T10:30:45.123Z",
  "level": "info",
  "message": "User logged in",
  "service": "my-app",
  "userId": 123,
  "email": "[email protected]"
}

File Rotation

import { Logger } from 'mega-logger';

const logger = new Logger({
  file: {
    directory: './logs',
    filename: 'app',
    maxSize: '10M', // Rotate when file exceeds 10MB
    maxFiles: 7, // Keep 7 days of logs
    interval: '1d', // Rotate daily
    compress: true, // Gzip rotated files
  },
});

Loki Integration

import { Logger } from 'mega-logger';

const logger = new Logger({
  loki: {
    host: 'http://localhost:3100',
    labels: {
      app: 'my-app',
      env: 'production',
    },
    batchSize: 100,
    flushInterval: 5000,
  },
});

OpenTelemetry

import { Logger } from 'mega-logger';

const logger = new Logger({
  openTelemetry: {
    enabled: true,
    serviceName: 'my-app',
    endpoint: 'http://localhost:4318/v1/traces',
  },
});

// Logs will automatically include trace_id and span_id
// when called within an active span
await logger.span('database-query', async () => {
  logger.info('Executing query');
  // ...
});

API Reference

Log Levels

logger.trace('Most verbose level');
logger.debug('Debug information');
logger.info('General information');
logger.success('Operation succeeded');
logger.warn('Warning message');
logger.error('Error occurred');
logger.fatal('Critical error');

Metadata

// Object metadata
logger.info('User action', { userId: 123, action: 'login' });

// Error objects
logger.error('Failed', new Error('Connection timeout'));

Child Loggers

const requestLogger = logger.child({
  requestId: 'abc-123',
  userId: 456,
});

requestLogger.info('Processing request'); // Includes requestId and userId

Timing Utilities

// Automatic timing with withTiming
const result = await logger.withTiming('operation', async () => {
  // Your async operation
  return someResult;
});

// Manual timing with startTimer
const stopTimer = logger.startTimer('long-operation');
// ... do work ...
const { duration, durationFormatted } = stopTimer();

Level Management

logger.setLevel('debug');
const currentLevel = logger.getLevel();

Transport Management

import { ConsoleTransport, FileTransport } from 'mega-logger';

// Add transport
logger.addTransport(new ConsoleTransport());

// Remove transport
logger.removeTransport('console');

// List transports
const transports = logger.getTransports();

Graceful Shutdown

// Flush all pending logs
await logger.flush();

// Close all transports
await logger.close();

Formatters

Built-in Formatters

import {
  PrettyFormatter,
  CompactPrettyFormatter,
  JsonFormatter,
  NdjsonFormatter,
  LogfmtFormatter,
} from 'mega-logger';

// Pretty (development)
new PrettyFormatter({ showIcons: true, colors: true });

// Compact pretty
new CompactPrettyFormatter();

// JSON (production)
new JsonFormatter({ pretty: false });

// NDJSON (newline-delimited JSON)
new NdjsonFormatter();

// Logfmt (key=value pairs)
new LogfmtFormatter();

Custom Formatters

import type { Formatter, LogEntry } from 'mega-logger';

class MyFormatter implements Formatter {
  format(entry: LogEntry): string {
    return `[${entry.level}] ${entry.message}`;
  }
}

Transports

Built-in Transports

import {
  ConsoleTransport,
  FileTransport,
  LokiTransport,
  OpenTelemetryTransport,
} from 'mega-logger';

Custom Transports

import type { Transport, LogEntry } from 'mega-logger';

class MyTransport implements Transport {
  name = 'my-transport';

  log(entry: LogEntry): void | Promise<void> {
    // Send log somewhere
  }

  async flush(): Promise<void> {
    // Flush pending logs
  }

  async close(): Promise<void> {
    // Cleanup
  }
}

Utilities

import {
  formatDuration,
  maskSensitiveData,
  generateTraceId,
  detectEnvironment,
  parseLogLevel,
} from 'mega-logger';

// Format milliseconds to human readable
formatDuration(1500); // "1.50s"

// Mask sensitive fields
maskSensitiveData({ password: 'secret123' }); // { password: 'se***23' }

// Generate trace IDs
generateTraceId(); // "a1b2c3d4e5f6..."

Best Practices

1. Use Structured Metadata

// Good
logger.info('User logged in', { userId: 123, method: 'oauth' });

// Avoid
logger.info(`User ${userId} logged in via ${method}`);

2. Use Appropriate Levels

  • trace - Extremely detailed tracing
  • debug - Debugging information
  • info - General operational messages
  • success - Successful operations (optional)
  • warn - Warning conditions
  • error - Error conditions
  • fatal - Critical errors requiring immediate attention

3. Create Child Loggers for Context

app.use((req, res, next) => {
  req.logger = logger.child({
    requestId: req.id,
    path: req.path,
  });
  next();
});

4. Don't Log Sensitive Data

// Use maskSensitiveData utility
import { maskSensitiveData } from 'mega-logger';

logger.info('Request received', maskSensitiveData(requestBody));

5. Always Flush Before Exit

process.on('SIGTERM', async () => {
  await logger.flush();
  process.exit(0);
});

TypeScript Support

Full TypeScript support with exported types:

import type {
  Logger,
  LogLevel,
  LogEntry,
  LogMetadata,
  Transport,
  Formatter,
  LoggerConfig,
} from 'mega-logger';

License

MIT