1.0.9 โข Published 5 months ago
loggerama3000 v1.0.9
loggerama3000 ๐ชตโจ
โจ 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
Option | Type | Default | Description |
---|---|---|---|
logName | string | 'app' | Name of the logger instance |
logDirectory | string | './logs' | Base directory for log files |
level | LogLevel | 'debug' | Minimum log level to record |
enableFileLogging | boolean | true | Enable file-based logging |
enableConsoleLogging | boolean | true | Enable console logging |
maxFileSize | number | 5MB | Maximum size of each log file |
maxFiles | number | 5 | Maximum number of log files to keep |
useDailyRotation | boolean | false | Enable daily log rotation |
separateErrorLog | boolean | true | Create separate error log file |
separateWarnLog | boolean | true | Create separate warning log file |
prettyPrint | boolean | false | Enable pretty printing of logs |
colorize | boolean | false | Enable colorized output |
silent | boolean | false | Disable all logging |
handleExceptions | boolean | false | Handle uncaught exceptions |
handleRejections | boolean | false | Handle unhandled rejections |
customTransports | Transport[] | undefined | Additional Winston transports |
customFormat | Format | undefined | Custom Winston format |
timestampFormat | string | undefined | Custom timestamp format |
locale | string | '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
- X (Twitter): @AGIManifesto
- LinkedIn: patgpt