2025-09-01 10:32:59 +00:00
# @push.rocks/smartlog 🚀
*The ultimate TypeScript logging solution for modern applications*
2024-04-14 17:48:56 +02:00
2025-09-01 10:32:59 +00:00
[](https://www.npmjs.com/package/@push .rocks/smartlog)
[](https://opensource.org/licenses/MIT)
2018-06-05 20:48:14 +02:00
2025-09-01 10:32:59 +00:00
> **smartlog** is a powerful, distributed, and extensible logging system designed for the cloud-native era. Whether you're debugging locally, monitoring production systems, or building complex microservices, smartlog adapts to your needs with style. 🎯
2024-04-14 17:48:56 +02:00
2026-02-14 15:52:57 +00:00
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/ ](https://community.foss.global/ ). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/ ](https://code.foss.global/ ) account to submit Pull Requests directly.
2025-09-01 10:32:59 +00:00
## 🌟 Why smartlog?
2024-04-14 17:48:56 +02:00
2025-09-01 10:32:59 +00:00
- **🎨 Beautiful Console Output**: Color-coded, formatted logs that are actually readable
2026-02-14 15:52:57 +00:00
- **🔌 Extensible Architecture**: Plug in any destination — databases, files, remote servers
2025-09-01 10:32:59 +00:00
- **🌍 Distributed by Design**: Built for microservices with correlation and context tracking
- **⚡ Zero-Config Start**: Works out of the box, scales when you need it
- **🎭 Interactive CLI Tools**: Spinners and progress bars that handle non-TTY environments gracefully
- **📊 Structured Logging**: JSON-based for easy parsing and analysis
- **🔍 Smart Filtering**: Log levels and context-based filtering
## 📦 Installation
```bash
2025-05-19 22:51:17 +00:00
# Using pnpm (recommended)
pnpm add @push .rocks/smartlog
# Using npm
2025-09-01 10:32:59 +00:00
npm install @push .rocks/smartlog
2024-04-14 17:48:56 +02:00
```
2025-09-01 10:32:59 +00:00
## 🚀 Quick Start
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
### Your First Logger
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
```typescript
import { Smartlog } from '@push .rocks/smartlog';
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
// Create a logger with context
const logger = new Smartlog({
logContext: {
company: 'MyStartup',
companyunit: 'Backend Team',
containerName: 'api-gateway',
environment: 'production',
runtime: 'node',
zone: 'eu-central'
}
});
2025-05-19 22:51:17 +00:00
2026-02-14 15:52:57 +00:00
// Enable console output
2025-09-01 10:32:59 +00:00
logger.enableConsole();
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
// Start logging!
2026-02-14 15:52:57 +00:00
await logger.log('info', '🎉 Application started successfully');
await logger.log('error', '💥 Database connection failed', {
2025-09-01 10:32:59 +00:00
errorCode: 'DB_TIMEOUT',
2026-02-14 15:52:57 +00:00
attemptCount: 3
2025-09-01 10:32:59 +00:00
});
```
2025-05-19 22:51:17 +00:00
2026-02-14 15:52:57 +00:00
### Using `createForCommitinfo`
2025-05-19 22:51:17 +00:00
2026-02-14 15:52:57 +00:00
If you're integrating with a build system that provides commit info, you can use the static factory method:
2025-09-01 10:32:59 +00:00
```typescript
2026-02-14 15:52:57 +00:00
import { Smartlog } from '@push .rocks/smartlog';
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
const logger = Smartlog.createForCommitinfo({
name: 'my-app',
version: '1.0.0',
description: 'My application'
});
logger.enableConsole();
await logger.log('lifecycle', '🔄 App starting...');
2025-09-01 10:32:59 +00:00
```
## 📚 Core Concepts
### Log Levels
smartlog supports semantic log levels for different scenarios:
```typescript
// Lifecycle events
2026-02-14 15:52:57 +00:00
await logger.log('lifecycle', '🔄 Container starting up...');
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
// Success states
2026-02-14 15:52:57 +00:00
await logger.log('success', '✅ Payment processed');
await logger.log('ok', '👍 Health check passed');
2025-09-01 10:32:59 +00:00
// Information and debugging
2026-02-14 15:52:57 +00:00
await logger.log('info', '📋 User profile updated');
await logger.log('note', '📌 Cache invalidated');
await logger.log('debug', '🔍 Query execution plan', { sql: 'SELECT * FROM users' });
2025-09-01 10:32:59 +00:00
// Warnings and errors
2026-02-14 15:52:57 +00:00
await logger.log('warn', '⚠️ Memory usage above 80%');
await logger.log('error', '❌ Failed to send email');
2025-09-01 10:32:59 +00:00
// Verbose output
2026-02-14 15:52:57 +00:00
await logger.log('silly', '🔬 Entering function processPayment()');
2025-09-01 10:32:59 +00:00
```
2026-02-14 15:52:57 +00:00
Available levels (from most to least verbose): `silly` , `debug` , `info` , `note` , `ok` , `success` , `warn` , `error` , `lifecycle`
### Log Types
Each log entry has a type that describes what kind of data it represents:
| Type | Description |
|------|-------------|
| `log` | Standard log message |
| `increment` | Counter/metric increment |
| `gauge` | Gauge measurement |
| `error` | Error event |
| `success` | Success event |
| `value` | Value recording |
| `finance` | Financial transaction |
| `compliance` | Compliance event |
2025-09-01 10:32:59 +00:00
### Log Groups for Correlation
Perfect for tracking request flows through your system:
```typescript
// Track a user request through multiple operations
const requestGroup = logger.createLogGroup('req-7f3a2b');
requestGroup.log('info', 'Received POST /api/users');
requestGroup.log('debug', 'Validating request body');
requestGroup.log('info', 'Creating user in database');
requestGroup.log('success', 'User created successfully', { userId: 'usr_123' });
2026-02-14 15:52:57 +00:00
// All logs in the group share the same group ID and transaction ID
```
### Log Context
Every log carries contextual information about the environment it was created in:
```typescript
interface ILogContext {
commitinfo?: ICommitInfo; // Build/version info
company?: string; // Company name
companyunit?: string; // Team or department
containerName?: string; // Container/service name
environment?: 'local' | 'test' | 'staging' | 'production';
runtime?: 'node' | 'chrome' | 'rust' | 'deno' | 'cloudflare_workers';
zone?: string; // Deployment zone/region
}
2025-05-19 22:51:17 +00:00
```
2018-01-28 04:43:55 +01:00
2025-09-01 10:32:59 +00:00
## 🎯 Log Destinations
2018-06-05 20:48:14 +02:00
2026-02-14 15:52:57 +00:00
smartlog routes log packages to any number of destinations simultaneously. Each destination implements the `ILogDestination` interface with a single `handleLog` method.
2025-09-01 10:32:59 +00:00
### Built-in Destinations
2024-04-14 17:48:56 +02:00
2025-09-01 10:32:59 +00:00
#### 🖥️ Local Console (Enhanced)
2018-01-28 04:43:55 +01:00
2026-02-14 15:52:57 +00:00
Beautiful, color-coded output for local development:
2024-04-14 17:48:56 +02:00
```typescript
2025-09-01 10:32:59 +00:00
import { DestinationLocal } from '@push .rocks/smartlog/destination-local';
2019-01-22 12:44:45 +01:00
2026-02-14 15:52:57 +00:00
const localDestination = new DestinationLocal();
2025-09-01 10:32:59 +00:00
logger.addLogDestination(localDestination);
2026-02-14 15:52:57 +00:00
// Output is color-coded per log level:
// 🔵 info: blue prefix, white text
// 🔴 error: red prefix, red text
// 🟢 ok/success: green prefix, green text
// 🟠 warn: orange prefix, orange text
// 🟣 note/debug: pink prefix, pink text
// 🔵 silly: blue background, blue text
```
The `DestinationLocal` also supports **reduced logging ** — a mode where repeated identical log messages are suppressed:
```typescript
const localDest = new DestinationLocal();
localDest.logReduced('Waiting for connection...'); // Logged
localDest.logReduced('Waiting for connection...'); // Suppressed
localDest.logReduced('Waiting for connection...'); // Suppressed
localDest.logReduced('Connected!'); // Logged (new message)
2024-04-14 17:48:56 +02:00
```
2025-09-01 10:32:59 +00:00
#### 📁 File Logging
2024-04-14 17:48:56 +02:00
2026-02-14 15:52:57 +00:00
Persist logs to files with timestamped entries:
2024-04-14 17:48:56 +02:00
```typescript
2025-09-01 10:32:59 +00:00
import { SmartlogDestinationFile } from '@push .rocks/smartlog/destination-file';
2025-05-19 22:51:17 +00:00
2026-02-14 15:52:57 +00:00
// Path MUST be absolute
const fileDestination = new SmartlogDestinationFile('/var/log/myapp/app.log');
2025-09-01 10:32:59 +00:00
logger.addLogDestination(fileDestination);
2026-02-14 15:52:57 +00:00
// Log entries are written as timestamped lines:
// 2024-01-15T10:30:00.000Z: Application started
// 2024-01-15T10:30:01.123Z: Processing request
2024-04-14 17:48:56 +02:00
```
2025-09-01 10:32:59 +00:00
#### 🌐 Browser DevTools
2024-04-14 17:48:56 +02:00
2025-09-01 10:32:59 +00:00
Optimized for browser environments with styled console output:
2019-01-22 12:44:45 +01:00
2025-09-01 10:32:59 +00:00
```typescript
import { SmartlogDestinationDevtools } from '@push .rocks/smartlog/destination-devtools';
const devtools = new SmartlogDestinationDevtools();
logger.addLogDestination(devtools);
2026-02-14 15:52:57 +00:00
// Uses CSS styling in browser console for beautiful, categorized output
// Different colors for error (red), info (pink), ok (green), success (green),
// warn (orange), and note (blue) levels
2025-09-01 10:32:59 +00:00
```
#### 📊 ClickHouse Analytics
2026-02-14 15:52:57 +00:00
Store logs in ClickHouse for powerful time-series analytics:
2024-04-14 17:48:56 +02:00
```typescript
2025-09-01 10:32:59 +00:00
import { SmartlogDestinationClickhouse } from '@push .rocks/smartlog/destination-clickhouse';
const clickhouse = await SmartlogDestinationClickhouse.createAndStart({
2026-02-14 15:52:57 +00:00
url: 'https://analytics.example.com:8123',
2025-09-01 10:32:59 +00:00
database: 'logs',
2026-02-14 15:52:57 +00:00
username: 'logger',
2025-09-01 10:32:59 +00:00
password: process.env.CLICKHOUSE_PASSWORD
});
2024-04-14 17:48:56 +02:00
2025-09-01 10:32:59 +00:00
logger.addLogDestination(clickhouse);
2019-01-22 12:44:45 +01:00
```
2025-09-01 10:32:59 +00:00
#### 🔗 Remote Receiver
2024-04-14 17:48:56 +02:00
2026-02-14 15:52:57 +00:00
Send logs to a centralized logging service with authenticated transport:
2025-05-19 22:51:17 +00:00
```typescript
2025-09-01 10:32:59 +00:00
import { SmartlogDestinationReceiver } from '@push .rocks/smartlog/destination-receiver';
const receiver = new SmartlogDestinationReceiver({
2026-02-14 15:52:57 +00:00
passphrase: process.env.LOG_PASSPHRASE,
receiverEndpoint: 'https://logs.mycompany.com/ingest'
2025-09-01 10:32:59 +00:00
});
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
logger.addLogDestination(receiver);
2025-05-19 22:51:17 +00:00
```
2025-05-15 19:53:29 +00:00
2026-02-14 15:52:57 +00:00
Logs are sent as authenticated JSON payloads with SHA-256 hashed passphrases.
2025-09-01 10:32:59 +00:00
### 🛠️ Custom Destinations
2025-05-15 19:53:29 +00:00
2026-02-14 15:52:57 +00:00
Build your own destination for any logging backend by implementing the `ILogDestination` interface:
2025-05-19 22:51:17 +00:00
```typescript
2026-02-14 15:52:57 +00:00
import type { ILogDestination, ILogPackage } from '@push .rocks/smartlog/interfaces';
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
class ElasticsearchDestination implements ILogDestination {
async handleLog(logPackage: ILogPackage): Promise<void> {
await this.client.index({
index: `logs-${new Date().toISOString().split('T')[0]}` ,
body: {
'@timestamp ': logPackage.timestamp,
level: logPackage.level,
message: logPackage.message,
context: logPackage.context,
data: logPackage.data,
correlation: logPackage.correlation
}
2025-05-19 22:51:17 +00:00
});
}
}
2026-02-14 15:52:57 +00:00
logger.addLogDestination(new ElasticsearchDestination());
2025-05-19 22:51:17 +00:00
```
2025-09-01 10:32:59 +00:00
## 🎨 Interactive Console Features
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
### Spinners
Create beautiful loading animations that degrade gracefully in CI/CD:
2025-05-19 22:51:17 +00:00
```typescript
2025-09-01 10:32:59 +00:00
import { SmartlogSourceInteractive } from '@push .rocks/smartlog/source-interactive';
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
const spinner = new SmartlogSourceInteractive();
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
// Basic usage
spinner.text('🔄 Fetching data from API...');
// ... perform async operation
spinner.finishSuccess('✅ Data fetched successfully!');
2026-02-14 15:52:57 +00:00
// Chain success and move to next task
spinner.text('📡 Connecting to database');
// ... connect
spinner.successAndNext('🔍 Running migrations');
// ... migrate
spinner.finishSuccess('🎉 Database ready!');
2025-09-01 10:32:59 +00:00
// Customize appearance
spinner
2026-02-14 15:52:57 +00:00
.setSpinnerStyle('dots') // 'dots' | 'line' | 'star' | 'simple'
2025-09-01 10:32:59 +00:00
.setColor('cyan') // any terminal color
2026-02-14 15:52:57 +00:00
.setSpeed(80); // animation speed in ms
spinner.text('🚀 Deploying application...');
2025-09-01 10:32:59 +00:00
// Handle failures
try {
await deployApp();
spinner.finishSuccess('✅ Deployed!');
} catch (error) {
spinner.finishFail('❌ Deployment failed');
}
```
### Progress Bars
Track long-running operations with style:
```typescript
import { SmartlogProgressBar } from '@push .rocks/smartlog/source-interactive';
// Create a progress bar
const progress = new SmartlogProgressBar({
total: 100,
2026-02-14 15:52:57 +00:00
width: 40, // Bar width in characters
complete: '█', // Fill character
incomplete: '░', // Empty character
showEta: true, // Show estimated time remaining
showPercent: true, // Show percentage
showCount: true // Show current/total count
2025-09-01 10:32:59 +00:00
});
// Update progress
for (let i = 0; i <= 100; i++) {
progress.update(i);
await someAsyncWork();
}
progress.complete();
2026-02-14 15:52:57 +00:00
// Or use increment for simpler tracking
2025-09-01 10:32:59 +00:00
const files = await getFiles();
2026-02-14 15:52:57 +00:00
const fileProgress = new SmartlogProgressBar({ total: files.length });
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
for (const file of files) {
2025-09-01 10:32:59 +00:00
await processFile(file);
2026-02-14 15:52:57 +00:00
fileProgress.increment();
2025-09-01 10:32:59 +00:00
}
2026-02-14 15:52:57 +00:00
fileProgress.complete();
2025-09-01 10:32:59 +00:00
```
### Non-Interactive Fallback
2026-02-14 15:52:57 +00:00
Both spinners and progress bars automatically detect non-interactive environments (CI/CD, Docker logs, piped output) and fall back to simple text output:
2025-09-01 10:32:59 +00:00
```
[Loading] Connecting to database
[Success] Connected to database
[Loading] Running migrations
Progress: 25% (25/100)
Progress: 50% (50/100)
Progress: 100% (100/100)
2026-02-14 15:52:57 +00:00
Completed: 100% (100/100)
2025-09-01 10:32:59 +00:00
```
2026-02-14 15:52:57 +00:00
Detection checks for: TTY capability, CI environment variables (GitHub Actions, Jenkins, GitLab CI, Travis, CircleCI), and `TERM=dumb` .
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
### Backward Compatibility
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
The `SmartlogSourceOra` class extends `SmartlogSourceInteractive` and provides a compatibility layer for code that previously used the `ora` npm package:
2025-09-01 10:32:59 +00:00
```typescript
2026-02-14 15:52:57 +00:00
import { SmartlogSourceOra } from '@push .rocks/smartlog/source-interactive';
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
const ora = new SmartlogSourceOra();
ora.oraInstance.start();
ora.oraInstance.succeed('Done!');
2025-09-01 10:32:59 +00:00
```
2025-05-19 22:51:17 +00:00
2026-02-14 15:52:57 +00:00
## 🔧 Advanced Features
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
### Minimum Log Level
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
Set a minimum log level that destinations can use to filter messages:
2025-09-01 10:32:59 +00:00
```typescript
const logger = new Smartlog({
2026-02-14 15:52:57 +00:00
logContext: { environment: 'production', runtime: 'node' },
minimumLogLevel: 'warn' // Destinations can check this to filter
2025-09-01 10:32:59 +00:00
});
2026-02-14 15:52:57 +00:00
// The minimumLogLevel is available as a public property
console.log(logger.minimumLogLevel); // 'warn'
2025-09-01 10:32:59 +00:00
```
### Increment Logging
2026-02-14 15:52:57 +00:00
Track metrics and counters alongside your logs:
2025-09-01 10:32:59 +00:00
```typescript
// Track API calls
logger.increment('info', 'api.requests', { endpoint: '/users', method: 'GET' });
2026-02-14 15:52:57 +00:00
// Track error types
2025-09-01 10:32:59 +00:00
logger.increment('error', 'payment.failed', { reason: 'insufficient_funds' });
```
2026-02-14 15:52:57 +00:00
Increment logs are routed to all destinations with `type: 'increment'` so analytics backends can aggregate them.
2025-09-01 10:32:59 +00:00
### Capture All Console Output
2026-02-14 15:52:57 +00:00
Redirect all `console.log` and `console.error` through smartlog:
2025-09-01 10:32:59 +00:00
```typescript
2026-02-14 15:52:57 +00:00
logger.enableConsole({
captureAll: true
2025-09-01 10:32:59 +00:00
});
2026-02-14 15:52:57 +00:00
console.log('This goes through smartlog as info!');
console.error('This goes through smartlog as error!');
// Strings containing "Error:" are automatically classified as error level
// All captured output is prefixed with "LOG =>" to prevent recursion
```
### Log Receiver Server
Accept authenticated log packages from remote services:
```typescript
import { SmartlogReceiver } from '@push .rocks/smartlog/receiver';
const receiver = new SmartlogReceiver({
smartlogInstance: logger,
passphrase: 'shared-secret',
validatorFunction: async (logPackage) => {
// Custom validation logic
return logPackage.context.company === 'MyCompany';
}
});
// Handle incoming authenticated log packages (e.g., from an HTTP endpoint)
app.post('/logs', async (req, res) => {
const result = await receiver.handleAuthenticatedLog(req.body);
res.json(result); // { status: 'ok' } or { status: 'error' }
});
// Or handle batches
app.post('/logs/batch', async (req, res) => {
await receiver.handleManyAuthenticatedLogs(req.body);
res.json({ status: 'ok' });
});
2025-09-01 10:32:59 +00:00
```
## 🏗️ Real-World Examples
### Microservice with Distributed Tracing
```typescript
import { Smartlog } from '@push .rocks/smartlog';
2025-05-19 22:51:17 +00:00
import { SmartlogDestinationClickhouse } from '@push .rocks/smartlog/destination-clickhouse';
2026-02-14 15:52:57 +00:00
import { DestinationLocal } from '@push .rocks/smartlog/destination-local';
2025-09-01 10:32:59 +00:00
// Initialize logger with service context
const logger = new Smartlog({
logContext: {
company: 'TechCorp',
companyunit: 'Platform',
containerName: 'user-service',
2026-02-14 15:52:57 +00:00
environment: 'production',
2025-09-01 10:32:59 +00:00
runtime: 'node',
2026-02-14 15:52:57 +00:00
zone: 'eu-central'
2025-09-01 10:32:59 +00:00
}
});
// Add ClickHouse for analytics
2025-05-19 22:51:17 +00:00
const clickhouse = await SmartlogDestinationClickhouse.createAndStart({
2026-02-14 15:52:57 +00:00
url: process.env.CLICKHOUSE_URL,
2025-09-01 10:32:59 +00:00
database: 'microservices_logs'
2025-05-19 22:51:17 +00:00
});
logger.addLogDestination(clickhouse);
2026-02-14 15:52:57 +00:00
// Add local console for container stdout
logger.addLogDestination(new DestinationLocal());
2025-05-15 19:53:29 +00:00
2025-09-01 10:32:59 +00:00
// Express middleware for request tracking
app.use((req, res, next) => {
2026-02-14 15:52:57 +00:00
const logGroup = logger.createLogGroup(req.headers['x-request-id'] || 'unknown');
2025-09-01 10:32:59 +00:00
logGroup.log('info', 'Incoming request', {
method: req.method,
path: req.path,
ip: req.ip
});
2026-02-14 15:52:57 +00:00
2025-09-01 10:32:59 +00:00
res.on('finish', () => {
logGroup.log('info', 'Request completed', {
statusCode: res.statusCode,
duration: Date.now() - req.startTime
});
});
2026-02-14 15:52:57 +00:00
2025-09-01 10:32:59 +00:00
next();
});
```
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
### CLI Tool with Progress Tracking
2025-05-15 19:53:29 +00:00
```typescript
2025-09-01 10:32:59 +00:00
import { Smartlog } from '@push .rocks/smartlog';
2025-05-19 22:51:17 +00:00
import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push .rocks/smartlog/source-interactive';
2025-09-01 10:32:59 +00:00
const logger = new Smartlog({
logContext: {
containerName: 'migration-tool',
2026-02-14 15:52:57 +00:00
environment: 'local',
runtime: 'node'
2025-09-01 10:32:59 +00:00
}
});
logger.enableConsole();
async function migrateDatabase() {
const spinner = new SmartlogSourceInteractive();
2026-02-14 15:52:57 +00:00
2025-09-01 10:32:59 +00:00
spinner.text('🔌 Connecting to database...');
await connectDB();
spinner.finishSuccess('✅ Connected to database');
2026-02-14 15:52:57 +00:00
2025-09-01 10:32:59 +00:00
spinner.text('📋 Loading migrations...');
const migrations = await getMigrations();
spinner.finishSuccess(`✅ Found ${migrations.length} migrations` );
2026-02-14 15:52:57 +00:00
2025-09-01 10:32:59 +00:00
const progress = new SmartlogProgressBar({
total: migrations.length,
width: 40,
showEta: true
});
2026-02-14 15:52:57 +00:00
2025-09-01 10:32:59 +00:00
for (const [index, migration] of migrations.entries()) {
2026-02-14 15:52:57 +00:00
await logger.log('info', `Running migration: ${migration.name}` );
2025-09-01 10:32:59 +00:00
await runMigration(migration);
progress.update(index + 1);
}
2026-02-14 15:52:57 +00:00
2025-09-01 10:32:59 +00:00
progress.complete();
2026-02-14 15:52:57 +00:00
await logger.log('success', '🎉 All migrations completed successfully!');
2025-09-01 10:32:59 +00:00
}
2025-05-19 22:51:17 +00:00
```
2025-09-01 10:32:59 +00:00
### Production Logging with Multiple Destinations
2025-05-15 19:53:29 +00:00
2025-05-19 22:51:17 +00:00
```typescript
2025-09-01 10:32:59 +00:00
import { Smartlog } from '@push .rocks/smartlog';
import { DestinationLocal } from '@push .rocks/smartlog/destination-local';
import { SmartlogDestinationFile } from '@push .rocks/smartlog/destination-file';
import { SmartlogDestinationReceiver } from '@push .rocks/smartlog/destination-receiver';
2025-05-19 22:51:17 +00:00
2025-09-01 10:32:59 +00:00
const logger = new Smartlog({
logContext: {
company: 'Enterprise Corp',
containerName: 'payment-processor',
environment: 'production',
runtime: 'node',
zone: 'us-east-1'
},
2026-02-14 15:52:57 +00:00
minimumLogLevel: 'info'
2025-09-01 10:32:59 +00:00
});
2025-05-15 19:53:29 +00:00
2026-02-14 15:52:57 +00:00
// Color-coded console for container logs
2025-09-01 10:32:59 +00:00
logger.addLogDestination(new DestinationLocal());
2025-05-15 19:53:29 +00:00
2025-09-01 10:32:59 +00:00
// File for audit trail
logger.addLogDestination(new SmartlogDestinationFile('/var/log/app/audit.log'));
2025-05-15 19:53:29 +00:00
2025-09-01 10:32:59 +00:00
// Central logging service
logger.addLogDestination(new SmartlogDestinationReceiver({
2026-02-14 15:52:57 +00:00
passphrase: process.env.LOG_PASSPHRASE,
receiverEndpoint: 'https://logs.enterprise.com/ingest'
2025-09-01 10:32:59 +00:00
}));
2025-05-19 22:51:17 +00:00
2026-02-14 15:52:57 +00:00
// Custom inline destination for critical alerts
2025-09-01 10:32:59 +00:00
logger.addLogDestination({
async handleLog(logPackage) {
if (logPackage.level === 'error' && logPackage.data?.critical) {
2026-02-14 15:52:57 +00:00
await sendSlackAlert(`🚨 Critical error: ${logPackage.message}` );
2025-09-01 10:32:59 +00:00
}
}
});
2025-05-15 19:53:29 +00:00
```
2026-02-14 15:52:57 +00:00
## 📖 API Reference
2025-05-15 19:53:29 +00:00
2026-02-14 15:52:57 +00:00
### Smartlog Class
2025-05-15 19:53:29 +00:00
2025-09-01 10:32:59 +00:00
```typescript
2026-02-14 15:52:57 +00:00
class Smartlog {
// Static factory
static createForCommitinfo(commitinfo: ICommitInfo): Smartlog;
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
// Constructor
constructor(options: {
logContext: ILogContext;
minimumLogLevel?: TLogLevel; // default: 'silly'
});
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
// Logging
log(level: TLogLevel, message: string, data?: any, correlation?: ILogCorrelation): Promise<void>;
increment(level: TLogLevel, message: string, data?: any, correlation?: ILogCorrelation): void;
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
// Configuration
enableConsole(options?: { captureAll: boolean }): void;
addLogDestination(destination: ILogDestination): void;
2025-05-15 19:53:29 +00:00
2026-02-14 15:52:57 +00:00
// Correlation
createLogGroup(transactionId?: string): LogGroup;
2024-04-14 17:48:56 +02:00
2026-02-14 15:52:57 +00:00
// Forwarding (for receiver pattern)
handleLog(logPackage: ILogPackage): Promise<void>;
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
// Instance identity
uniInstanceId: string;
logContext: ILogContext;
minimumLogLevel: TLogLevel;
2025-09-01 10:32:59 +00:00
}
```
2019-01-22 12:44:45 +01:00
2026-02-14 15:52:57 +00:00
### LogGroup Class
2019-01-22 12:44:45 +01:00
2024-04-14 17:48:56 +02:00
```typescript
2026-02-14 15:52:57 +00:00
class LogGroup {
groupId: string; // Auto-generated unique ID
transactionId: string; // The transaction ID passed at creation
smartlogRef: Smartlog; // Reference to the parent Smartlog
2025-09-01 10:32:59 +00:00
2026-02-14 15:52:57 +00:00
log(level: TLogLevel, message: string, data?: any): void;
2025-09-01 10:32:59 +00:00
}
2019-01-22 12:44:45 +01:00
```
2026-02-14 15:52:57 +00:00
### ILogDestination Interface
2019-01-22 12:44:45 +01:00
2025-05-19 22:51:17 +00:00
```typescript
2026-02-14 15:52:57 +00:00
interface ILogDestination {
handleLog(logPackage: ILogPackage): Promise<void>;
2025-09-01 10:32:59 +00:00
}
2025-05-19 22:51:17 +00:00
```
2019-01-22 12:44:45 +01:00
2026-02-14 15:52:57 +00:00
### ILogPackage Interface
2019-01-28 02:03:11 +01:00
2025-09-01 10:32:59 +00:00
```typescript
2026-02-14 15:52:57 +00:00
interface ILogPackage<T = unknown> {
timestamp: number; // Unix timestamp in milliseconds
type: TLogType; // 'log' | 'increment' | 'gauge' | ...
context: ILogContext; // Environment context
level: TLogLevel; // Log severity
correlation: ILogCorrelation; // Correlation metadata
message: string; // The log message
data?: T; // Optional structured data
2025-09-01 10:32:59 +00:00
}
2025-05-19 22:51:17 +00:00
```
2024-04-14 17:48:56 +02:00
2026-02-14 15:52:57 +00:00
### Available Log Levels
2024-04-14 17:48:56 +02:00
2026-02-14 15:52:57 +00:00
| Level | Description | Use Case |
|-------|-------------|----------|
| `silly` | Ultra-verbose | Function entry/exit, variable dumps |
| `debug` | Debug info | Development-time diagnostics |
| `info` | Informational | Standard operational messages |
| `note` | Notable events | Important but non-critical events |
| `ok` | Success confirmation | Health checks, validations |
| `success` | Major success | Completed operations |
| `warn` | Warnings | Degraded performance, approaching limits |
| `error` | Errors | Failures requiring attention |
| `lifecycle` | Lifecycle events | Start, stop, restart, deploy |
2024-04-14 17:48:56 +02:00
2026-02-14 15:52:57 +00:00
## License and Legal Information
2024-04-14 17:48:56 +02:00
2026-02-14 15:52:57 +00:00
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE ](./LICENSE ) file.
2024-04-14 17:48:56 +02:00
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
2019-01-22 12:49:09 +01:00
2026-02-14 15:52:57 +00:00
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
2020-06-07 13:23:56 +00:00
2024-04-14 17:48:56 +02:00
### Company Information
2020-06-07 13:23:56 +00:00
2026-02-14 15:52:57 +00:00
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
2018-01-28 04:43:55 +01:00
2026-02-14 15:52:57 +00:00
For any legal inquiries or further information, please contact us via email at hello@task .vc.
2018-01-28 04:43:55 +01:00
2026-02-14 15:52:57 +00:00
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.