Loggerfy is a lightweight and customizable logging library designed to provide structured logs with rich metadata. It simplifies the process of logging errors, warnings, and information while ensuring consistency across your application.
npm install loggerfy> A simple and structured logging library for Node.js applications
Loggerfy is a lightweight library that helps you create structured logs with a consistent format. Perfect for applications that need an organized and easy-to-implement logging system.
``bash`
npm install loggerfy
`js
// CommonJS
const { Loggerfy } = require('loggerfy');
// ES Modules
import { Loggerfy } from 'loggerfy';
`
`js
// Create an instance
const logger = new Loggerfy();
// Log an error
logger.error()
.setCode('AUTH_001')
.setMessage('User authentication failed')
.setDetail('Invalid credentials provided')
.setMetadata({ userId: 123 })
.write();
`
Loggerfy offers three logging levels:
`js
// Information
logger.info()
.setCode('APP_001')
.setMessage('Application started')
.setDetail('Server listening on port 3000')
.write();
// Warning
logger.warn()
.setCode('CONFIG_001')
.setMessage('Using default configuration')
.setDetail('Configuration file not found')
.write();
// Error
logger.error()
.setCode('DB_001')
.setMessage('Database connection error')
.setDetail('Timeout after 30 seconds')
.write();
`
| Method | Description | Required? |
|--------|-------------|-----------|
| setCode(code) | Sets a unique code for the log entry | Yes |setMessage(message)
| | Sets the main message | Yes |setDetail(detail)
| | Adds additional details | Yes |setMetadata(object)
| | Adds contextual data | No |write()
| | Writes the log to the console | Yes* |getLog()
| | Returns the log as a JSON string without printing | Yes* |
*Either write() or getLog() must be called to complete the logging operation.
If you need the log as a string instead of printing it to the console:
`js
// Get log as JSON string
const logString = logger.error()
.setCode('AUTH_001')
.setMessage('User authentication failed')
.setDetail('Invalid credentials provided')
.setMetadata({ userId: 123 })
.getLog();
// Now you can use the string however you want
sendToExternalService(logString);
`
All logs are generated in JSON format:
`json`
{
"timestamp": "2023-11-15T14:30:45.123Z",
"id": "550e8400-e29b-41d4-a716-446655440000",
"code": "AUTH_001",
"message": "User authentication failed",
"detail": "Invalid credentials provided",
"payload": { "userId": 123 },
"level": "ERROR",
"severity": "ERROR",
"service": "my-service",
"environment": "development"
}
Loggerfy automatically detects the environment and service name:
`js
// Configure environment variables
process.env.SERVICE_NAME = "user-api";
process.env.NODE_ENV = "production";
// Logs will include these values
`
You can save logs to a custom repository:
`js
import { Loggerfy, LoggerfyRepository, LogEntry } from 'loggerfy';
// Implement your repository
class MyRepository implements LoggerfyRepository {
async save(log: LogEntry): Promise
// Save the log to your database
await db.logs.insert(log);
}
}
// Create the logger with your repository
const logger = new Loggerfy(new MyRepository());
// Use it normally
logger.info()
.setCode('USER_001')
.setMessage('User created')
.setDetail('New record in database')
.write();
`
`js
import { Loggerfy } from 'loggerfy';
// Environment configuration
process.env.SERVICE_NAME = "payment-service";
const logger = new Loggerfy();
function processPayment(userId, amount) {
try {
// Payment processing logic
// Success log
logger.info()
.setCode('PAYMENT_001')
.setMessage('Payment processed successfully')
.setDetail(Payment of $${amount} processed)`
.setMetadata({ userId, amount, timestamp: new Date() })
.write();
return true;
} catch (error) {
// Error log
logger.error()
.setCode('PAYMENT_ERR_001')
.setMessage('Payment processing failed')
.setDetail(error.message)
.setMetadata({ userId, amount, errorStack: error.stack })
.write();
return false;
}
}
1. Use consistent codes - Create a coding system for your logs (e.g., AUTH_001, DB_001)
2. Include context - Use setMetadata to add relevant information for debugging
3. Use the appropriate level - Don't log everything as an error, use info and warn appropriately
4. Choose the right output method - Use write() for console output or getLog()` when you need the log as a string
Visit our GitHub repository for more information or to report issues.