Releases: ProMehedi/bun-hono-api-starter
v1.2.1
Release Notes - Version 1.2.1
🎉 New Feature: Comprehensive Logging System
Version 1.2.1 introduces a powerful, production-ready logging system built with Winston and daily log rotation. This release adds comprehensive HTTP request logging and structured logging capabilities to help you monitor and debug your API effectively.
✨ What's New
📝 Winston Logger Integration
- Structured JSON Logging: Production-ready structured logging with JSON format for easy parsing and analysis
- Human-Readable Console Output: Beautiful, colorized console logs for development with timestamps and metadata
- Daily Log Rotation: Automatic daily log file rotation with compression to manage disk space efficiently
- Multiple Log Levels: Support for
debug,info,warn, anderrorlog levels with configurable defaults
🔄 HTTP Request Logging Middleware
Every HTTP request is now automatically logged with comprehensive details:
- HTTP method (GET, POST, PUT, DELETE, etc.)
- Request path and full URL
- Response status code
- Request duration (in milliseconds)
- User agent information
- Client IP address (supports Cloudflare and proxy headers)
Example Log Entry:
{
"timestamp": "2026-01-06T10:30:45.123Z",
"level": "info",
"message": "HTTP Request",
"method": "POST",
"path": "/api/v1/users/login",
"url": "http://localhost:8000/api/v1/users/login",
"status": 200,
"duration": "45ms",
"userAgent": "Mozilla/5.0...",
"ip": "127.0.0.1"
}📊 Organized Log Files
The logger creates separate log files for different purposes:
-
App Logs (
app-YYYY-MM-DD.log)- General application logs (info, warn, error)
- Max size: 50MB per file
- Retention: 14 days
- Compressed after rotation
-
Error Logs (
error-YYYY-MM-DD.log)- Error-level logs only
- Max size: 20MB per file
- Retention: 30 days
- Compressed after rotation
-
Debug Logs (
debug-YYYY-MM-DD.log)- Debug-level logs (only when
LOG_LEVEL=debug) - Max size: 100MB per file
- Retention: 3 days (short retention due to verbosity)
- Compressed after rotation
- Debug-level logs (only when
-
Exception Logs (
exceptions-YYYY-MM-DD.log)- Uncaught exceptions
- Max size: 20MB per file
- Retention: 30 days
-
Rejection Logs (
rejections-YYYY-MM-DD.log)- Unhandled promise rejections
- Max size: 20MB per file
- Retention: 30 days
⚙️ Flexible Configuration
Configure logging behavior using environment variables:
LOG_LEVEL (Optional):
debug- Most verbose, includes debug logsinfo- Standard logging (default in production)warn- Warnings and errors onlyerror- Errors only- Default:
debugin development,infoin production
LOG_TO_FILE (Optional):
console- Log to console onlyfile- Log to files onlyboth- Log to both console and files (default)auto- Console in development, files in production- Default:
both
🔍 Context Logger Helper
Added createContextLogger utility function for structured logging with custom context:
import { createContextLogger } from '~/utils/logger'
const contextLogger = createContextLogger({ userId: '123', requestId: 'abc' })
contextLogger.info('User action', { action: 'login' })
// Logs: { userId: '123', requestId: 'abc', action: 'login' }📦 Dependencies Added
- winston v3.19.0 - Powerful logging library for Node.js
- winston-daily-rotate-file v5.0.0 - Daily log rotation transport for Winston
📁 File Structure Changes
New Files
utils/logger.ts- Winston logger configuration and setupmiddlewares/logger.middlewares.ts- HTTP request logging middlewarelogs/- Directory for log files (created automatically)logs/.audit/- Audit files for log rotation tracking
Updated Files
server.ts- Added logger middleware integrationpackage.json- Added Winston dependencies
🚀 Migration Guide
For New Projects
No migration needed! The logger is automatically enabled and will start logging immediately.
For Existing Projects
-
Install dependencies:
bun install
-
Optional: Configure logging in your
.envfile:LOG_LEVEL=info LOG_TO_FILE=both
-
Create logs directory (optional, created automatically):
mkdir -p logs/.audit
-
Add to .gitignore (if not already present):
logs/
📝 Usage Examples
Development Setup
LOG_LEVEL=debug
LOG_TO_FILE=bothThis will show verbose logs in the console and also save them to files.
Production Setup
LOG_LEVEL=info
LOG_TO_FILE=fileThis will only log to files, reducing console noise and improving performance.
Debugging Setup
LOG_LEVEL=debug
LOG_TO_FILE=consoleThis will show all logs in the console for quick debugging.
🎯 Benefits
- Better Observability: Track all HTTP requests and responses with detailed metadata
- Easier Debugging: Structured logs make it easy to find and analyze issues
- Production Ready: Automatic log rotation prevents disk space issues
- Flexible Configuration: Adapt logging to your environment needs
- Performance Monitoring: Request duration logging helps identify slow endpoints
- Security Auditing: IP and user agent logging helps track suspicious activity
🔧 Technical Details
- Logs are stored in the
logs/directory at the project root - Old log files are automatically compressed (
.gz) after rotation - Audit files are stored in
logs/.audit/for rotation tracking - Logger automatically handles uncaught exceptions and unhandled rejections
- Exit on handled exceptions in production (configurable)
📚 Documentation
For complete documentation on the logging feature, see the Logging section in the README.
🙏 Thank You
Thank you for using Bun + Hono API Starter! If you have any questions or feedback, please open an issue on GitHub.
Full Changelog: v1.2.0...v1.2.1
v1.2.0
TypeScript Fixes:
- ✅ Fixed
IUserinterface type incompatibility - changedSchema.Types.ObjectIdtoTypes.ObjectIdfor proper TypeScript type checking - ✅ Fixed Mongoose pre-save hook - removed deprecated
next()callback in favor of modern async/await pattern - ✅ Improved type safety with correct Mongoose TypeScript types
- ✅ All TypeScript compilation errors resolved
Code Quality & Developer Experience:
- 🔧 Updated user model to use modern Mongoose async hook pattern
- 📝 Fixed typo in comment ("Heiger" → "Higher")
- 🎨 Added Prettier code formatting with comprehensive configuration
- 🪝 Integrated Husky git hooks for automated code quality checks
- pre-commit hook: Automatically runs
format:checkandtypecheckbefore commits - pre-push hook: Ensures code formatting and type checking pass before pushing
- pre-commit hook: Automatically runs
- 📦 Added format scripts:
format(auto-fix) andformat:check(verify only) - ✅ Automatic code quality enforcement prevents committing unformatted or type-unsafe code
v1.1.0
Security Improvements:
- 🔒 Fixed critical mass assignment vulnerability -
isAdmincan no longer be set during registration - 🔐 Added JWT token expiration (7 days) with proper validation
- 🛡️ Implemented rate limiting middleware to prevent brute force attacks
- 🔒 Added secure headers middleware (XSS, clickjacking, MIME sniffing protection)
- 🛡️ Added CSRF protection for production environments
- 🔐 Fixed JWT secret validation - now throws error if missing
- 🔒 Fixed password hash leak in profile update response
- 🛡️ Improved CORS configuration with environment-based origin restrictions
- 🔍 Fixed error handler stack trace exposure logic
- ✅ Added comprehensive input validation (email format, password length)
Code Quality:
- 📦 Removed deprecated
@types/mongoosedependency - 🔄 Standardized environment variable access to
process.env - ✅ Improved TypeScript types and error handling
- 🔄 Updated to modern Hono JWT API (
sign/verifyinstead of deprecatedJwt) - 📝 Enhanced error messages and validation feedback
Dependencies:
- Updated to Hono v4.11.3
- Mongoose v9.1.1 (includes built-in TypeScript types)