@supercat1337/logger
v1.0.0
Published
A simple logging utility for Node.js applications.
Downloads
56
Readme
Logger
A lightweight and flexible logging library for Node.js applications, providing file-based logging with timestamp formatting and timezone support.
Installation
npm install @supercat1337/loggerFeatures
- 📝 Simple file-based logging with different log levels
- 🕒 Configurable timestamp formatting with timezone support
- 📁 Automatic log file path conversion utilities
- 🚀 Promise-based async logging operations
- 🔧 Customizable output directory and file extensions
- ✅ TypeScript support with full type definitions
Quick Start
import { Logger } from '@supercat1337/logger';
// Create a logger instance
const logger = new Logger('./app.log');
// Log messages at different levels
await logger.info('Application started');
await logger.warn('Low disk space');
await logger.error('Failed to connect to database');
// Close the logger when done
await logger.close();API Reference
Logger Class
The main Logger class for writing log messages to files.
Constructor
new Logger(filePath: string, options?: {
useDate?: boolean;
timeZone?: any;
})filePath: Path to the log fileoptions.useDate: Whether to include timestamps in log messages (default:true)options.timeZone: Timezone for timestamps
Methods
log(message: string, level?: string): Promise<void>- Write a log message with specified levelerror(message: string): Promise<void>- Write an error messagewarn(message: string): Promise<void>- Write a warning messageinfo(message: string): Promise<void>- Write an info messageclose(): Promise<boolean>- Close the logger and wait for pending writes
Utility Functions
convertFilePathToLogFilePath()
Convert a file path to a log file path by appending .log extension.
convertFilePathToLogFilePath(
filePath: string,
suffix?: string,
options?: {
outputDir?: string;
extension?: string;
}
): stringDate Formatting Functions
formatDate(date: Date, format?: string, timeZone?: string): string- Format a date with custom format and timezonegetDateString(timeZone?: string): string- Get current date asYYYY-MM-DDgetDateTimeString(timeZone?: string): string- Get current datetime asYYYY-MM-DD HH:MM:SSgetDateTimeStringForFileName(timeZone?: string): string- Get datetime for filenames asYYYY-MM-DD_HH-MM-SSgetCurrentTimeZone(): string- Get current system timezone
Usage Examples
Basic Logging
import { Logger } from '@supercat1337/logger';
const logger = new Logger('./logs/app.log');
// Log with different levels
await logger.info('User logged in');
await logger.warn('API response slow');
await logger.error('Database connection failed');
// Custom log level
await logger.log('Debug message', 'debug');With Timezone Configuration
import { Logger } from '@supercat1337/logger';
// Logger with specific timezone
const logger = new Logger('./app.log', {
useDate: true,
timeZone: 'America/New_York'
});
await logger.info('Log with New York timezone');File Path Conversion
import { convertFilePathToLogFilePath } from '@supercat1337/logger';
// Convert source file path to log file path
const logPath = convertFilePathToLogFilePath('/src/app.js');
// Returns: /src/app.js.log
// With custom output directory and suffix
const customLogPath = convertFilePathToLogFilePath(
'/src/app.js',
'errors',
{ outputDir: '/logs', extension: '.txt' }
);
// Returns: /logs/app.errors.txtDate Formatting
import {
getDateString,
getDateTimeString,
formatDate
} from '@supercat1337/logger';
// Get formatted dates
const today = getDateString(); // "2024-01-15"
const now = getDateTimeString(); // "2024-01-15 14:30:45"
// Custom formatting
const customDate = formatDate(
new Date(),
'YYYY/MM/DD HH:mm:ss',
'Europe/London'
);Error Handling
The logger handles write errors gracefully:
try {
await logger.error('Something went wrong');
} catch (err) {
console.error('Failed to write log:', err);
}Closing the Logger
Always close the logger to ensure all pending writes are completed:
// In an async context
await logger.close();
// Or with then/catch
logger.close()
.then(() => console.log('Logger closed'))
.catch(err => console.error('Error closing logger:', err));License
MIT
