logbuddy-js
Version:
๐ชต Your friendly neighborhood logging companion for Node.js applications with intelligent file rotation and flexible configuration
302 lines (224 loc) โข 8.11 kB
Markdown
# ๐ชต LogBuddy.js
> **Your friendly neighborhood logging companion for Node.js applications**
[](https://www.npmjs.com/package/logbuddy-js)
[](https://opensource.org/licenses/ISC)
[](https://nodejs.org/)
LogBuddy.js is a lightweight, configurable logging library for Node.js that provides intelligent file rotation, multiple log levels, and flexible configuration options. Whether you're building a small script or a large application, LogBuddy.js has got your logging needs covered! ๐ฏ
## โจ Features
- ๐ **Smart File Rotation** - Automatic log rotation based on file size or time intervals
- ๐ **Multiple Log Levels** - Debug, Info, Warning, Error, and Fatal levels
- โ๏ธ **Flexible Configuration** - JSON-based configuration with builder patterns
- ๐ **Custom File Naming** - Configurable file prefixes for organized logs
- ๐ **Zero Dependencies** - Lightweight and fast
- ๐พ **Size-based Rolling** - From 1KB to 100MB thresholds
- โฐ **Time-based Rolling** - Minutely, hourly, daily, weekly, monthly, or yearly rotation
## ๐ Quick Start
### Installation
```bash
npm install logbuddy-js
```
### Basic Usage
```javascript
const { Logger, LogLevel } = require("logbuddy-js");
// Create a logger with default settings
const logger = Logger.with_defaults();
// Start logging!
logger.info("Hello from Log Buddy! ๐");
logger.error("Something went wrong ๐ฑ");
logger.debug("Debug information");
```
### With Configuration
```javascript
const {
Logger,
LogConfig,
LogLevel,
RollingSizeOptions,
RollingTimeOptions,
} = require("logbuddy-js");
// Create custom configuration
const config = LogConfig.with_defaults()
.with_log_level(LogLevel.Debug)
.with_file_prefix("MyApp_")
.with_rolling_config({
size_threshold: RollingSizeOptions.TenMB,
time_threshold: RollingTimeOptions.Daily,
});
const logger = Logger.with_config(config);
```
## ๐ Configuration
### JSON Configuration
Create a `config.json` file:
```json
{
"level": 1,
"file_prefix": "MyApp_",
"rolling_config": {
"size_threshold": 10485760,
"time_threshold": 86400
}
}
```
Load from file:
```javascript
const { Logger, LogConfig } = require("logbuddy-js");
const logger = Logger.with_config(LogConfig.from_file("./config.json"));
```
### Log Levels
| Level | Value | Description |
| --------- | ----- | ------------------------------ |
| `Debug` | 0 | Detailed debugging information |
| `Info` | 1 | General information messages |
| `Warning` | 2 | Warning messages |
| `Error` | 3 | Error messages |
| `Fatal` | 4 | Critical error messages |
### Rolling Size Options
```javascript
const { RollingSizeOptions } = require("logbuddy-js");
// Pre-defined size constants
RollingSizeOptions.OneKB; // 1,024 bytes
RollingSizeOptions.FiveKB; // 5,120 bytes
RollingSizeOptions.TenKB; // 10,240 bytes
RollingSizeOptions.HundredKB; // 102,400 bytes
RollingSizeOptions.OneMB; // 1,048,576 bytes
RollingSizeOptions.FiveMB; // 5,242,880 bytes (default)
RollingSizeOptions.TenMB; // 10,485,760 bytes
RollingSizeOptions.HundredMB; // 104,857,600 bytes
```
### Rolling Time Options
```javascript
const { RollingTimeOptions } = require("logbuddy-js");
// Pre-defined time intervals
RollingTimeOptions.Minutely; // 60 seconds
RollingTimeOptions.Hourly; // 3,600 seconds (default)
RollingTimeOptions.Daily; // 86,400 seconds
RollingTimeOptions.Weekly; // 604,800 seconds
RollingTimeOptions.Monthly; // 2,592,000 seconds
RollingTimeOptions.Yearly; // 31,104,000 seconds
```
## ๐ฏ API Reference
### Logger Class
```javascript
const logger = Logger.with_config(config);
// Logging methods
logger.debug("Debug message");
logger.info("Info message");
logger.warn("Warning message");
logger.error("Error message");
logger.critical("Critical message");
// Access configuration
console.log(logger.level); // Current log level
console.log(logger.file_prefix); // File prefix
console.log(logger.size_threshold); // Size threshold in bytes
console.log(logger.time_threshold); // Time threshold in seconds
```
### LogConfig Class
```javascript
const config = LogConfig.with_defaults()
.with_log_level(LogLevel.Info)
.with_file_prefix("MyApp_")
.with_rolling_config({
size_threshold: RollingSizeOptions.FiveMB,
time_threshold: RollingTimeOptions.Hourly,
});
// Load from JSON
const config = LogConfig.from_file("./config.json");
const config = LogConfig.from_json(jsonObject);
```
### RollingConfig Class
```javascript
const rolling = RollingConfig.with_defaults()
.with_size_threshold(RollingSizeOptions.TenMB)
.with_time_threshold(RollingTimeOptions.Daily);
// Access thresholds
console.log(rolling.size_threshold); // Size in bytes
console.log(rolling.time_threshold); // Time in seconds
```
## ๐ Examples
### Example 1: Web Server Logging
```javascript
const { Logger, LogConfig, LogLevel } = require("logbuddy-js");
const config = LogConfig.with_defaults()
.with_log_level(LogLevel.Info)
.with_file_prefix("WebServer_")
.with_rolling_config({
size_threshold: 5242880, // 5MB
time_threshold: 86400, // Daily rotation
});
const logger = Logger.with_config(config);
// In your server code
app.get("/api/users", (req, res) => {
logger.info(`API request: GET /api/users from ${req.ip}`);
try {
const users = getUsersFromDB();
logger.debug(`Retrieved ${users.length} users`);
res.json(users);
} catch (error) {
logger.error(`Database error: ${error.message}`);
res.status(500).json({ error: "Internal server error" });
}
});
```
### Example 2: Debug Mode Development
```javascript
const { Logger, LogConfig, LogLevel } = require("logbuddy-js");
const isDevelopment = process.env.NODE_ENV === "development";
const config = LogConfig.with_defaults()
.with_log_level(isDevelopment ? LogLevel.Debug : LogLevel.Info)
.with_file_prefix("App_")
.with_rolling_config({
size_threshold: 1048576, // 1MB for development
time_threshold: 3600, // Hourly rotation
});
const logger = Logger.with_config(config);
logger.debug("This only appears in development mode");
logger.info("This appears in all modes");
```
### Example 3: Error Monitoring
```javascript
const { Logger, LogConfig, LogLevel } = require("logbuddy-js");
const errorLogger = Logger.with_config(
LogConfig.with_defaults()
.with_log_level(LogLevel.Error)
.with_file_prefix("Errors_")
.with_rolling_config({
size_threshold: 10485760, // 10MB
time_threshold: 86400, // Daily
})
);
process.on("uncaughtException", (error) => {
errorLogger.fatal(`Uncaught Exception: ${error.message}`);
errorLogger.fatal(`Stack: ${error.stack}`);
});
process.on("unhandledRejection", (reason, promise) => {
errorLogger.error(`Unhandled Rejection at: ${promise}, reason: ${reason}`);
});
```
## ๐งช Testing
Run the test example:
```bash
npm start
```
This will run the test file and demonstrate the logging functionality.
## ๐ค Contributing
We welcome contributions! Here's how you can help:
1. **Fork** the repository
2. **Create** a feature branch (`git checkout -b feature/amazing-feature`)
3. **Commit** your changes (`git commit -m 'Add amazing feature'`)
4. **Push** to the branch (`git push origin feature/amazing-feature`)
5. **Open** a Pull Request
### Development Setup
```bash
git clone https://github.com/itsmaazashraf/logbuddy-js.git
cd logbuddy-js
npm install
```
## ๐ License
This project is licensed under the ISC License - see the [LICENSE](LICENSE) file for details.
## ๐ Issues & Support
Found a bug or need help? Please open an issue on our [GitHub repository](https://github.com/itsmaazashraf/logbuddy-js/issues).
## ๐ Acknowledgments
- Built with โค๏ธ for the Node.js community
- Inspired by the need for simple, effective logging
---
**Happy Logging! ๐ชตโจ**