Fast β’ Lightweight β’ Zero Dependencies β’ TypeScript Native
π Documentation Β· β‘ Quick Start Β· β¨ Features Β· π¬ Community
- β‘ Super lightweight β minimal footprint, fast execution
- π― Simple API β intuitive methods like
info(),warn(), etc. - π¨ Custom formatting β plain text or JSON
- β±οΈ Automatic timestamps
- π Multiple transports
- π§© Child loggers for modular logging
- π§΅ Async writes β keeps Node responsive
- π Small, safe, dependency-light design
- π Custom log levels with color support
npm install zarioπ Other Package Managers
# Using Yarn
yarn add zario
# Using pnpm
pnpm add zario
# Using bun
bun add zarioimport { Logger, ConsoleTransport } from "zario";
const logger = new Logger({
level: "info",
colorize: true,
transports: [new ConsoleTransport()],
prefix: "[MyApp]",
});
// Start logging
logger.info("π Server started on port 3000");
logger.warn("β οΈ High memory usage detected");
logger.error("β Database connection failed", { code: 500 });Output:
[MyApp] INFO π Server started on port 3000
[MyApp] WARN β οΈ High memory usage detected
[MyApp] ERROR β Database connection failed { code: 500 }| Level | Method | Use Case | Example |
|---|---|---|---|
| π DEBUG | logger.debug() |
Detailed debugging info | Variable values, function calls |
| βΉοΈ INFO | logger.info() |
General information | Server started, user logged in |
logger.warn() |
Warning messages | Deprecated API usage, high load | |
| β ERROR | logger.error() |
Error conditions | Failed requests, exceptions |
| π FATAL | logger.fatal() |
Critical failures | System crash, data corruption |
| π SILENT | logger.silent() |
Suppresses logging | Disable logging for specific scenarios |
| π BORING | logger.boring() |
Low priority info |
Example:
logger.debug("Debugging user authentication flow");
logger.info("User successfully authenticated");
logger.warn("Session about to expire");
logger.error("Failed to save user data");
logger.fatal("Database connection lost");Perfect when you want separate logs per module or request:
const main = new Logger({ prefix: "[APP]" });
const db = main.createChild({ prefix: "[DB]" });
main.info("App initialized");
db.error("Connection timeout");Output:
[APP] [INFO] App initialized
[APP][DB] [ERROR] Connection timeoutBuilt-in timer utility for measuring execution time:
const logger = new Logger({ prefix: "[PERFORMANCE]" });
// Create a timer
const timer = logger.startTimer("Database query");
// Simulate some work
await databaseQuery();
// End the timer - logs the duration automatically
timer.end(); // Output: [PERFORMANCE] [INFO] Database query took 150msThe timer is idempotent - calling end() multiple times will only log the duration once.
Auto-configure based on NODE_ENV:
// Development: colorized, debug level, console transport, sync mode
process.env.NODE_ENV = 'development';
const devLogger = new Logger();
// Production: JSON, warn level, file transport, async mode
process.env.NODE_ENV = 'production';
const prodLogger = new Logger();Auto-configuration behavior:
- Development:
level: 'debug',colorize: true,json: false,asyncMode: false,transports: [new ConsoleTransport()] - Production:
level: 'warn',colorize: false,json: true,asyncMode: true,transports: [new ConsoleTransport(), new FileTransport({path: './logs/app.log'})]
All settings can be overridden with explicit options.
|
|
|
πΊ Console Transport
const logger = new Logger({
transports: [
new ConsoleTransport({ colorize: true })
]
});Perfect for development and debugging.
π File Transport
const logger = new Logger({
transports: [
new FileTransport({
path: './logs/app.log',
maxSize: 10485760, // 10MB in bytes
maxFiles: 5
})
]
});Ideal for production logging and auditing.
π HTTP Transport
const logger = new Logger({
transports: [
new HttpTransport({
url: 'https://api.example.com/logs',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token-here'
},
timeout: 10000, // Request timeout in ms
retries: 3 // Number of retry attempts
})
]
});Send logs to a remote HTTP endpoint with retry logic and timeout handling.
π Custom Transport
const logger = new Logger({
transports: [{
type: 'custom',
instance: {
write: (log, formatter) => {
// Send to external service
sendToDatadog(log);
}
}
}]
});Integrate with any logging service.
|
π·οΈ Metadata Support logger.info('User login', {
userId: 12345,
ip: '192.168.1.1',
timestamp: new Date()
}); |
π Error Tracking try {
riskyOperation();
} catch (error) {
logger.error('Operation failed', error);
} |
|
π― Prefix/Namespace const logger = new Logger({
prefix: '[MyService]'
}); |
βοΈ Environment Aware const logger = new Logger({
level: process.env.LOG_LEVEL || 'info'
}); |
Define Custom Log Levels
Create your own log levels with specific priorities and colors for more granular logging.
import { Logger } from 'zario';
const logger = new Logger({
level: 'info',
customLevels: {
'success': 6, // Higher priority than error (5).
'verbose': 1, // Lower priority than debug (2).
'critical': 7, // Highest priority.
},
customColors: {
'success': 'green',
'verbose': 'cyan',
'critical': 'brightRed',
},
transports: [
new ConsoleTransport()
]
});
// Using custom levels.
logger.logWithLevel('success', 'This is a success message in green!');
logger.logWithLevel('verbose', 'This is a verbose message in cyan');
logger.logWithLevel('critical', 'This is a critical message in bright red');Log Level Filtering
Set the logger's level to a custom level to filter messages based on their priority.
// Only logs levels with priority >= 7 (critical in this case).
const highLevelLogger = new Logger({
level: 'critical',
customLevels: {
'success': 6,
'verbose': 1,
'critical': 7,
},
transports: [
new ConsoleTransport()
]
});
// This will NOT be shown (verbose has priority 1 < critical threshold 7).
highLevelLogger.logWithLevel('verbose', 'This will not appear');
// This WILL be shown (critical has priority 7 >= threshold 7).
highLevelLogger.logWithLevel('critical', 'This critical message appears');Child Logger with Custom Levels
Child loggers inherit custom levels and colors from their parent, and can also have their own.
const parentLogger = new Logger({
level: 'info',
customLevels: {
'parent_custom': 6,
},
customColors: {
'parent_custom': 'blue',
},
transports: [
new ConsoleTransport()
]
});
// Child will inherit parent's custom levels and can add its own.
const childLogger = parentLogger.createChild({
customLevels: {
'child_custom': 7, // Add child-specific level.
},
customColors: {
'child_custom': 'red',
}
});
childLogger.logWithLevel('parent_custom', 'Inherited from parent');
childLogger.logWithLevel('child_custom', 'Defined in child');
import express from 'express';
import Logger from 'zario';
const app = express();
const logger = new Logger({ prefix: '[API]' });
app.use((req, res, next) => {
const reqLogger = logger.createChild({ prefix: `[${req.method} ${req.url}]` });
reqLogger.info("Incoming request");
next();
});
app.get("/", (req, res) => {
res.send("Hello!");
});
app.listen(3000, () => {
logger.info("API running on port 3000");
});Perfect for:
|
import Logger from 'zario';
const logger = new Logger({
level: 'info',
transports: [new ConsoleTransport()]
});
export async function handler(event) {
logger.info('Lambda invoked', {
requestId: event.requestId
});
try {
const result = await processEvent(event);
logger.info('Processing complete');
return result;
} catch (error) {
logger.error('Processing failed', error);
throw error;
}
}Perfect for:
|
import Logger from 'zario';
const logger = new Logger({
colorize: true,
prefix: '[CLI]'
});
async function buildProject() {
logger.info('Starting build process...');
logger.debug('Reading config file');
logger.info('Compiling TypeScript...');
logger.info('Bundling assets...');
logger.info('β
Build completed successfully!');
}Perfect for:
|
import Logger from 'zario';
// Create service-specific loggers
const userService = new Logger({
prefix: '[UserService]'
});
const paymentService = new Logger({
prefix: '[PaymentService]'
});
const orderService = new Logger({
prefix: '[OrderService]'
});
// Use in distributed system
userService.info('User created', { id: 123 });
paymentService.info('Payment processed');
orderService.info('Order placed');Perfect for:
|
[2025-01-23 10:22:20] [INFO] User logged inconst logger = new Logger({ json: true });Output:
{
"timestamp": "2025-01-23T10:22:20Z",
"level": "info",
"message": "User logged in"
}/src
/logs
/modules
database.js
users.js
logger.js
server.jsimport Logger from "zario";
export const logger = new Logger({
prefix: "[API]",
transports: [new ConsoleTransport()],
});import Logger from "zario";
describe("Logger", () => {
it("should log messages", () => {
const logger = new Logger({ timestamp: false });
logger.info("Testing logger");
});
});| Option | Type | Description |
|---|---|---|
| level | string |
Log level threshold |
| json | boolean |
Output in JSON format |
| timestamp | boolean |
Include timestamps |
| prefix | string |
Prepended label |
| transports | array |
Where logs are written (with transport-specific options like path, maxSize, maxFiles for file transport) |
| asyncMode | boolean |
Whether to enable asynchronous logging mode for better performance under heavy logging |
| customLevels | object |
Define custom log levels and their priorities |
| customColors | object |
Assign colors to custom log levels |
| createChild() | method |
Creates a scoped logger |
| setAsyncMode() | method |
Toggles asynchronous logging mode at runtime |
| startTimer() | method |
Creates a timer to measure execution duration |
| π Resource | π Description | π Link |
|---|---|---|
| π Usage Guide | Complete guide with examples and best practices | Read β |
| βοΈ Configuration | All configuration options explained in detail | Read β |
| π― API Reference | Full API documentation with type definitions | Read β |
| πΌ Use Cases | Real-world examples and implementation patterns | Read β |
| π Migration Guide | Migrate from other logging libraries | Read β |
| π Custom Transports | Build your own transport implementations | Read β |
|
|
|
π³οΈ Vote for features: Have a feature request? Open an issue and let us know!
We β€οΈ contributions! Whether it's bug reports, feature requests, or code contributions.
|
π Report Bugs Found a bug? Report it β |
π‘ Request Features Have an idea? Suggest it β |
π Improve Docs Fix a typo? Submit PR β |
π¬ Join Discussion Questions? Discuss β |
Follow these steps if you want to work on the project locally:
# Clone the repository
git clone https://github.com/Dev-Dami/zario.git
# Navigate into the project
cd zario
# Install dependencies
npm install
# Run tests
npm test
# Build the project
npm run buildThis project is licensed under the MIT License - see the LICENSE file for full details.
MIT License - feel free to use this in your projects!
If Zario made your logging easier, consider:
β Star this repository to show your support
π¦ Share on Twitter to spread the word
β Buy us a coffee to fuel development