1.0.9 โ€ข Published 5 months ago

loggerama3000 v1.0.9

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

loggerama3000 ๐Ÿชตโœจ

Publish Package npm version Tests codecov semantic-release: angular License: MIT TypeScript Winston Bun


โœจ Features

  • ๐Ÿ”’ Type-Safe: Built with TypeScript for complete type safety
  • ๐ŸŽฏ Environment-Aware: Different configurations for development, production, and test
  • ๐Ÿ“ File Rotation: Automatic log file rotation with size and date-based options
  • ๐ŸŽจ Pretty Printing: Optional pretty printing for JSON logs
  • ๐Ÿšจ Error Handling: Separate error and warning log files
  • ๐Ÿ”„ Daily Rotation: Optional daily log file rotation
  • ๐Ÿ’พ Path Safety: Type-safe path handling for log files
  • ๐Ÿ›ก๏ธ Secure: Proper file permissions and error handling

๐Ÿ“ฆ Installation

NPM

npm install loggerama3000

Bun

bun add loggerama3000

Yarn

yarn add loggerama3000

๐Ÿš€ Quick Start

import { createLogger } from 'loggerama3000';

// Create a logger with default options
const logger = createLogger();

// Log messages with different levels
logger.info('Application started');
logger.debug('Loading configuration', { configPath: '/app/config.json' });
logger.warn('Cache miss', { key: 'user:1234' });
logger.error('Failed to connect to database', new Error('Connection timeout'));

๐Ÿงฉ Use Cases

๐ŸŒ Web API Logging

// api/users.ts
import { createLogger } from 'loggerama3000';

const logger = createLogger({
  logName: 'users-api',
  logDirectory: './logs',
  prettyPrint: process.env.NODE_ENV !== 'production'
});

export async function getUser(userId: string) {
  logger.info(`Fetching user with ID: ${userId}`);
  
  try {
    // Fetch user logic here
    const user = await database.findUser(userId);
    
    if (!user) {
      logger.warn(`User not found: ${userId}`);
      return null;
    }
    
    logger.info(`Successfully retrieved user: ${userId}`);
    return user;
  } catch (error) {
    logger.error(`Failed to fetch user: ${userId}`, { 
      error: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined
    });
    throw error;
  }
}

๐Ÿ”„ Next.js Server Component

// app/dashboard/page.tsx
import { createLogger } from 'loggerama3000';

const logger = createLogger({
  logName: 'dashboard',
  level: process.env.NODE_ENV === 'production' ? 'info' : 'debug'
});

export default async function DashboardPage() {
  logger.info('Rendering dashboard page');
  
  try {
    const data = await fetchDashboardData();
    logger.debug('Dashboard data fetched successfully', { dataLength: data.length });
    
    return <DashboardComponent data={data} />;
  } catch (error) {
    logger.error('Failed to fetch dashboard data', { error });
    return <ErrorComponent message="Failed to load dashboard" />;
  }
}

๐Ÿงช Testing with Silent Logger

// __tests__/user-service.test.ts
import { createLogger } from 'loggerama3000';
import { UserService } from '../services/user-service';

describe('UserService', () => {
  test('getUser returns user data', async () => {
    // Create a silent logger for tests
    const logger = createLogger({
      logName: 'test-user-service',
      silent: true,
      logDirectory: './test-logs'
    });
    
    const userService = new UserService(logger);
    const user = await userService.getUser('123');
    
    expect(user).toBeDefined();
    expect(user.id).toBe('123');
  });
});

โš™๏ธ Configuration

Basic Configuration

const logger = createLogger({
  logName: 'my-app',
  logDirectory: './logs',
  level: 'info',
  enableFileLogging: true,
  enableConsoleLogging: true
});

๐ŸŒ Environment-Specific Configuration

import { MB } from 'loggerama3000/utils';

// Development (default)
const devLogger = createLogger({
  level: 'debug',
  prettyPrint: true,
  colorize: true
});

// Production
const prodLogger = createLogger({
  level: 'info',
  useDailyRotation: true,
  maxFileSize: MB(10), // 10MB
  maxFiles: 10
});

// Test
const testLogger = createLogger({
  level: 'debug',
  silent: true // Disable logging in tests
});

๐Ÿ”ง Advanced Features

import { MB } from 'loggerama3000/utils';

const logger = createLogger({
  // Basic settings
  logName: 'my-app',
  logDirectory: './logs',
  level: 'info',

  // File handling
  enableFileLogging: true,
  maxFileSize: MB(5),
  maxFiles: 5,
  useDailyRotation: true,

  // Separate log files
  separateErrorLog: true,
  separateWarnLog: true,

  // Console output
  enableConsoleLogging: true,
  prettyPrint: true,
  colorize: true,

  // Formatting
  timestampFormat: 'YYYY-MM-DD HH:mm:ss',
  locale: 'en-US',

  // Error handling
  handleExceptions: true,
  handleRejections: true
});

๐Ÿ” Type Safety Features

loggerama3000 provides strong type safety features:

import { createLogger } from 'loggerama3000';
import { LogLevel } from 'loggerama3000/types';

// Type-safe log levels
const level: LogLevel = 'info'; // Only valid levels allowed

// Type-safe paths
const logger = createLogger({
  logDirectory: '/var/log/my-app', // Converted to SafePath internally
  logName: 'api-server'
});

// The logger guarantees that log files will be created with proper permissions
// and in the correct location with type safety throughout the codebase

๐Ÿ“š API Reference

createLogger(options?: LoggerOptions)

Creates a new logger instance with the specified options.

Options

OptionTypeDefaultDescription
logNamestring'app'Name of the logger instance
logDirectorystring'./logs'Base directory for log files
levelLogLevel'debug'Minimum log level to record
enableFileLoggingbooleantrueEnable file-based logging
enableConsoleLoggingbooleantrueEnable console logging
maxFileSizenumber5MBMaximum size of each log file
maxFilesnumber5Maximum number of log files to keep
useDailyRotationbooleanfalseEnable daily log rotation
separateErrorLogbooleantrueCreate separate error log file
separateWarnLogbooleantrueCreate separate warning log file
prettyPrintbooleanfalseEnable pretty printing of logs
colorizebooleanfalseEnable colorized output
silentbooleanfalseDisable all logging
handleExceptionsbooleanfalseHandle uncaught exceptions
handleRejectionsbooleanfalseHandle unhandled rejections
customTransportsTransport[]undefinedAdditional Winston transports
customFormatFormatundefinedCustom Winston format
timestampFormatstringundefinedCustom timestamp format
localestring'en-US'Locale for timestamp formatting

createSimpleLogger(env?: Environment)

Creates a simple logger with environment-specific defaults.

import { createSimpleLogger } from 'loggerama3000';

const logger = createSimpleLogger('production');
// Creates a production-optimized logger with reasonable defaults

Utility Functions

import { MB, createSafePath, joinSafePaths } from 'loggerama3000/utils';

// Convert megabytes to bytes
const maxSize = MB(10); // 10MB in bytes

// Create a type-safe path
const logPath = createSafePath('/var/log/my-app');

// Join paths safely
const fullPath = joinSafePaths(logPath, 'errors');

๐Ÿ“Š Log Format Examples

Standard Log Entry

2023-02-24 21:45:12 INFO: User authenticated successfully

JSON Structured Logging

2023-02-24 21:46:33 INFO: {"userId":123,"action":"login","ip":"192.168.1.1","browser":"Chrome"}

Pretty Printed JSON (Development)

< wow "userId" such 123, "action" such "login", "ip" such "192.168.1.1", "browser" such "Chrome" >

๐Ÿ’ป Environment Support

  • Node.js >=16.0.0
  • Bun >=1.0.0
  • TypeScript >=4.5.0

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details on how to get started.

๐Ÿ“„ License

This project is licensed under the MIT License - see the license file for details.

๐Ÿ‘จโ€๐Ÿ’ป Author

Patrick Kelly


1.0.9

5 months ago

1.0.8

5 months ago

1.0.7

5 months ago