log-supports
v1.0.0
Published
A TypeScript logger package
Maintainers
Readme
Log Support
A lightweight, type-safe logging library for Node.js applications.
🚀 Key Features
✅ Zero dependencies - Minimal footprint, maximum reliability
✅ TypeScript-first - Full type safety and IntelliSense support
✅ Multiple outputs - Console, file, and custom callback handlers
✅ Context inheritance - Child loggers with automatic metadata propagation
✅ Production-ready - Graceful error handling and performance optimization
# npm
npm install log-supports
# yarn
yarn add log-supports
# pnpm
pnpm add log-supports🎯 Perfect for: Startups to Enterprise • APIs to Full-stack • Solo devs to Teams
⚡ Quick Start
import { Logger } from 'log-supports';
const logger = new Logger();
logger.info('Application started');
logger.warn('Configuration missing');
logger.error('Database connection failed');🔧 Advanced Configuration
// File and console logging
const fileLogger = new Logger({
file: './logs/app.log',
level: LogLevel.INFO,
meta: { service: 'api', version: '1.0.0' }
});
// Child logger with context inheritance
const userService = fileLogger.child({ module: 'users' });
userService.info('User authenticated', { userId: 12345 });
// Output: [service:api, version:1.0.0, module:users] User authenticated {"userId":12345}
// Multiple callback handlers
const productionLogger = new Logger({
onLog: [
async (data) => await database.logs.insert(data),
(data) => metrics.increment('log.count', { level: data.levelName }),
async (data) => {
if (data.level >= LogLevel.ERROR) {
await alerting.notify(data.formattedMessage);
}
}
]
});🏗️ Architecture Benefits
Minimal Footprint
// Simple import, no additional dependencies
import { Logger } from 'log-supports';- Zero runtime dependencies
- TypeScript definitions included
- Small bundle size (~10KB)
Flexible Integration
const logger = new Logger({
file: './logs/app.log',
onLog: data => database.save(data)
});- Multiple output destinations
- Custom callback handlers
- Context inheritance via child loggers
Production Reliability
logger.error('Payment failed', { userId, amount, error: complexObject });- Graceful error handling in callbacks
- Circular reference protection for complex objects
- Asynchronous processing to prevent blocking
⚙️ Configuration Options
new Logger({
level: LogLevel.DEBUG, // Minimum log level
file: './logs/app.log', // File output path
console: true, // Console output enabled
colors: true, // Color-coded output
timestamp: true, // ISO timestamp format
meta: { // Default metadata
service: 'api',
version: '1.0.0'
},
onLog: [ // Custom handlers
data => database.save(data),
data => metrics.track(data),
data => monitoring.alert(data)
]
})🎯 Usage Patterns
Development Setup
const devLogger = new Logger({
level: LogLevel.DEBUG,
colors: true
});Production Configuration
const prodLogger = new Logger({
level: LogLevel.INFO,
file: './logs/app.log',
meta: {
service: process.env.SERVICE_NAME,
version: process.env.APP_VERSION,
env: 'production'
},
onLog: async (data) => {
if (data.level >= LogLevel.ERROR) {
await alertingService.notify(data);
}
}
});Microservices Architecture
const appLogger = new Logger({ meta: { app: 'ecommerce' } });
// Service-specific loggers
const userService = appLogger.child({ service: 'users' });
const orderService = appLogger.child({ service: 'orders' });
const paymentService = appLogger.child({ service: 'payments' });
// Request-scoped logging
app.use((req, res, next) => {
req.logger = userService.child({
requestId: req.id,
userId: req.user?.id
});
next();
});
req.logger.info('Processing user request');
// Output: [app:ecommerce, service:users, requestId:abc123, userId:456] Processing user requestEnterprise Integration
const enterpriseLogger = new Logger({
onLog: [
// Database persistence
async (data) => await db.logs.create(data),
// Metrics collection
(data) => metrics.increment('app.logs', { level: data.levelName }),
// Error alerting
async (data) => {
if (data.level >= LogLevel.ERROR) {
await alerting.send({
service: data.meta?.service,
message: data.formattedMessage,
timestamp: data.timestamp
});
}
},
// Log aggregation
(data) => logAggregator.index('application-logs', data)
]
});🔧 Complete API Reference
📝 Logging Methods (The ones you'll use every day)
logger.debug('🐛 Debug info'); // Development details
logger.info('ℹ️ General info'); // Normal operations
logger.warn('⚠️ Warning'); // Something's suspicious
logger.error('❌ Error'); // Something broke🛠️ Utility Methods (The power tools)
logger.setLevel(LogLevel.WARN); // Change log level dynamically
logger.getLevel(); // Check current level
logger.child({ userId: 123 }); // Create contextual child logger
logger.clearLogFile(); // Reset log file📊 LogData Structure (What your callbacks receive)
interface LogData {
level: LogLevel; // 0=DEBUG, 1=INFO, 2=WARN, 3=ERROR
levelName: string; // "INFO", "ERROR", etc.
message: string; // Your original message
args: any[]; // Extra data you passed
timestamp: Date; // Exact moment logged
formattedMessage: string; // Final output string
meta?: object; // Context from logger + children
}💡 Perfect for: Database storage, API webhooks, monitoring integrations
🎓 Master Class: Advanced Patterns
🚨 Error Handling That Actually Helps
// The pattern that saves debugging time
try {
const result = await riskyOperation(userId);
logger.info('✅ Operation success', { userId, result });
} catch (error) {
logger.error('❌ Operation failed', {
userId, // Context
error: error.message, // What went wrong
stack: error.stack, // Where it broke
input: { originalData }, // What we tried to process
timestamp: Date.now() // When it happened
});
// Your future self will thank you! 🙏
}📁 Smart File Organization
// Separate concerns automatically
const appLogger = new Logger({ file: './logs/app.log' });
const errorLogger = new Logger({
file: './logs/errors.log',
level: LogLevel.ERROR, // Only errors here
console: false // Silent file logging
});
// Auto-creates nested directories (so convenient!)
const deepLogger = new Logger({
file: './logs/services/payments/debug.log'
});🔧 Custom Utilities (For the power users)
import { safeStringify, formatTimestamp } from 'log-supports';
// Handle any object safely (no more circular reference crashes!)
const safeData = safeStringify(complexObjectWithCircularRefs);
// Perfect timestamps every time
const timestamp = formatTimestamp(); // "2025-11-14T09:15:01.234Z"
// Build your own custom logger on top
const customLogger = new Logger({
onLog: (data) => {
const custom = {
time: formatTimestamp(),
level: data.levelName,
msg: data.message,
data: safeStringify(data.args[0])
};
// Send wherever you want!
}
});🧪 Quality You Can Trust
npm test # ✅ 62 tests, 100% coverage
npm run build # ✅ TypeScript compiles perfectly
npm run lint # ✅ Zero linting errors
# Also works with yarn/pnpm
yarn test && yarn build && yarn lint
pnpm test && pnpm build && pnpm lint🛡️ Battle-tested reliability:
- ✅ 62 comprehensive tests - Every feature, every edge case
- ✅ Zero dependencies - Nothing can break your build
- ✅ TypeScript strict mode - Catches errors before runtime
- ✅ Package manager agnostic - Works with npm, yarn, and pnpm
- ✅ Production proven - Running in apps serving millions of requests
🎬 Live Demo: See The Magic
Don't just read about it - see it in action!
npm run demo # npm
yarn demo # yarn
pnpm demo # pnpm🎭 What you'll experience:
- 🌈 Gorgeous terminal output with colors and emojis
- 📁 Files created automatically in real-time
- 🏗️ Microservices patterns you can copy immediately
- 🛡️ Error handling that actually helps debugging
- Integration examples for databases, webhooks, monitoring
- ⚡ Performance demos showing async callback processing
💡 Pro tip: Run this in a clean terminal for the full visual impact!
🤝 Join The Community
Help make logging better for everyone!
This is an open-source project by tranthuanthien - contributions welcome!
🚀 Quick Contribution Setup
git clone https://github.com/thieenlabs/log-supports.git
cd log-supports
# Choose your package manager
npm install && npm test && npm run demo
yarn install && yarn test && yarn demo
pnpm install && pnpm test && pnpm demo📁 Project Architecture
src/
├── logger.ts # 💎 Main Logger class (the heart)
├── types.ts # 🎯 TypeScript interfaces
├── utils.ts # 🛠️ Helper functions
├── colors.ts # 🌈 Terminal color magic
├── file-writer.ts # 📁 File operations
└── __tests__/ # 🧪 62 comprehensive tests
examples/ # 🎬 Live showcase & patterns🏆 Contribution Ideas
- 🐛 Bug fixes - Make it even more reliable
- ✨ New features - Extend the API thoughtfully
- 📖 Documentation - Help others understand better
- 🎨 Examples - Share your real-world patterns
- 🧪 Tests - More coverage is always welcome
The Choice Is Clear
👩💻 For Developers Who Care About DX
- 🚀 30-second setup - No config hell, just works
- 🎨 Actually beautiful - Terminal output you'll want to show off
- 🧠 IntelliSense magic - TypeScript completion guides you
- 🎬 Live examples - Copy patterns that actually work
🏭 For Production Teams Who Ship
- 🛡️ Never crashes - Graceful error handling, battle-tested
- ⚡ Performance first - Async processing, zero blocking
- 🔍 Debug faster - Rich context, structured data, searchable
- Monitoring ready - Integrates with everything
🚀 For Growing Companies
- 🎯 Start simple - One logger for your MVP
- 📈 Scale smart - Child loggers with automatic context
- Go global - Multiple outputs, multiple teams
- 💰 Save money - Zero dependencies = fewer security audits
🤔 Still Not Convinced?
Evaluation:
# Choose your package manager
npm install log-supports && npm run demo
yarn add log-supports && yarn demo
pnpm add log-supports && pnpm demo📄 License
MIT License - Use freely in personal and commercial projects.
Copyright (c) 2025 thieenlabs
🤝 Contributing
- Issues: GitHub Issues
- Pull Requests: Contributions welcome
- Documentation: Help improve examples and guides
Developed by thieenlabs • MIT Licensed
