Compare commits

...

14 Commits

Author SHA1 Message Date
d1c05fb9ae 3.1.8
Some checks failed
Default (tags) / security (push) Successful in 31s
Default (tags) / test (push) Failing after 1m2s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-20 19:40:31 +00:00
f81971d148 fix(devDependencies): Update devDependencies for tstest and Node types 2025-05-20 19:40:31 +00:00
aa6a27970a 3.1.7
Some checks failed
Default (tags) / security (push) Successful in 26s
Default (tags) / test (push) Failing after 1m3s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-20 19:27:01 +00:00
b31d9f0c36 fix(ts_destination_local): Update debug log color: set textColor to pink in DestinationLocal. 2025-05-20 19:27:01 +00:00
e6cef68a26 3.1.6
Some checks failed
Default (tags) / security (push) Successful in 29s
Default (tags) / test (push) Failing after 1m4s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-20 19:26:12 +00:00
aa327efeac fix(ts_destination_local): Update debug prefix color in DestinationLocal: change from gray to pink for improved visibility. 2025-05-20 19:26:12 +00:00
7cbc64ed8d 3.1.5
Some checks failed
Default (tags) / security (push) Successful in 40s
Default (tags) / test (push) Failing after 1m5s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-20 19:24:39 +00:00
2c49ef49c2 fix(core): Maintain and verify project metadata and commit info consistency 2025-05-20 19:24:38 +00:00
823784e6b6 3.1.4
Some checks failed
Default (tags) / security (push) Successful in 41s
Default (tags) / test (push) Failing after 1m5s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-20 16:45:11 +00:00
a98f48409d fix(DestinationLocal): Fix debug log rendering, add fallback for unknown log levels, and correct error prefix typo in local destination 2025-05-20 16:45:11 +00:00
a2ae8c0c83 3.1.3
Some checks failed
Default (tags) / security (push) Successful in 39s
Default (tags) / test (push) Failing after 1m5s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-19 22:51:17 +00:00
6ef2d961a6 fix(documentation): Update API reference and enhance README with detailed examples and usage instructions 2025-05-19 22:51:17 +00:00
f80ec7ddfe 3.1.2
Some checks failed
Default (tags) / security (push) Successful in 44s
Default (tags) / test (push) Failing after 1m5s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-16 15:01:57 +00:00
f2823c2645 fix(tests): Update test imports and devDependencies to use @git.zone/tstest/tapbundle 2025-05-16 15:01:56 +00:00
20 changed files with 1474 additions and 1372 deletions

300
API.md Normal file
View File

@ -0,0 +1,300 @@
# @push.rocks/smartlog API Reference
This document provides a detailed reference for all exports and APIs available in the @push.rocks/smartlog package and its submodules.
## Core Module (`@push.rocks/smartlog`)
The core module provides the main logging functionality.
### Classes
#### `Smartlog`
Main logger class for creating, managing, and routing logs.
```typescript
import { Smartlog } from '@push.rocks/smartlog';
const logger = new Smartlog({
logContext: {
company: 'MyCompany',
environment: 'production',
// ...other context properties
},
minimumLogLevel: 'info' // Optional, defaults to 'silly'
});
```
**Constructor Options:**
- `logContext`: Object containing context information about the environment
- `minimumLogLevel`: Optional minimum log level to process (defaults to 'silly')
**Methods:**
- `log(logLevel, message, data?, correlation?)`: Log a message with optional data and correlation
- `increment(logLevel, message, data?, correlation?)`: Log an increment counter
- `addLogDestination(destination)`: Add a custom log destination
- `enableConsole(options?)`: Enable console logging (with optional stdout/stderr capture)
- `createLogGroup(transactionId?)`: Create a log group for related logs
- `handleLog(logPackage)`: Handle a pre-formatted log package
**Static Methods:**
- `createForCommitinfo(commitinfo)`: Create a logger with commit information
#### `LogGroup`
Groups related logs together for better traceability.
```typescript
import { Smartlog } from '@push.rocks/smartlog';
const logger = new Smartlog({/*...*/});
const logGroup = logger.createLogGroup('transaction-123');
logGroup.log('info', 'Starting process');
// All logs in this group will share the same transaction ID
```
**Methods:**
- `log(logLevel, message, data?)`: Log a message within this group
- `increment(logLevel, message, data?)`: Log an increment within this group
#### `ConsoleLog`
Implementation of `ILogDestination` that logs to console.
## Interfaces Module (`@push.rocks/smartlog/interfaces`)
This module provides all type definitions and interfaces used by Smartlog.
### Types
- `TLogType`: Available log types
- `'log' | 'increment' | 'gauge' | 'error' | 'success' | 'value' | 'finance' | 'compliance'`
- `TLogLevel`: Available log levels
- `'silly' | 'info' | 'debug' | 'note' | 'ok' | 'success' | 'warn' | 'error' | 'lifecycle'`
- `TEnvironment`: Available environments
- `'local' | 'test' | 'staging' | 'production'`
- `TRuntime`: Available runtime environments
- `'node' | 'chrome' | 'rust' | 'deno' | 'cloudflare_workers'`
### Interfaces
#### `ILogContext`
Metadata about the environment where logging occurs.
```typescript
interface ILogContext {
commitinfo?: ICommitInfo;
company?: string;
companyunit?: string;
containerName?: string;
environment?: TEnvironment;
runtime?: TRuntime;
zone?: string;
}
```
#### `ILogCorrelation`
Information for correlating related logs.
```typescript
interface ILogCorrelation {
id: string;
type: 'none' | 'service' | 'build' | 'infrastructure' | 'cdn';
instance?: string;
group?: string;
transaction?: string;
}
```
#### `ILogPackage<T = unknown>`
The standard log package format.
```typescript
interface ILogPackage<T = unknown> {
timestamp: number;
type: TLogType;
context: ILogContext;
level: TLogLevel;
correlation: ILogCorrelation;
message: string;
data?: T;
}
```
#### `ILogDestination`
Interface for implementing custom log destinations.
```typescript
interface ILogDestination {
handleLog: (logPackage: ILogPackage) => Promise<void>;
}
```
## Interactive Console Module (`@push.rocks/smartlog/source-interactive`)
This module provides interactive console components like spinners and progress bars.
### Classes
#### `SmartlogSourceInteractive`
Creates interactive spinners for CLI applications.
```typescript
import { SmartlogSourceInteractive } from '@push.rocks/smartlog/source-interactive';
const spinner = new SmartlogSourceInteractive();
spinner.text('Loading data...');
// Later
spinner.finishSuccess('Data loaded successfully!');
```
**Methods:**
- `text(message)`: Sets the spinner text and starts it if not running
- `finishSuccess(message?)`: Completes the spinner with success message
- `finishFail(message?)`: Completes the spinner with failure message
- `successAndNext(message)`: Marks success and starts a new spinner
- `failAndNext(message)`: Marks failure and starts a new spinner
- `setSpinnerStyle(style)`: Sets spinner style ('dots', 'line', 'star', 'simple')
- `setColor(color)`: Sets the spinner color
- `setSpeed(ms)`: Sets the animation speed
#### `SmartlogProgressBar`
Creates progress bars for CLI applications.
```typescript
import { SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
const bar = new SmartlogProgressBar({
total: 100,
width: 40,
showEta: true
});
bar.update(50); // Update to 50%
bar.increment(10); // Increment by 10 units
bar.complete(); // Complete the progress bar
```
**Constructor Options:**
- `total`: Total number of items/steps
- `width`: Width of the bar in characters
- `complete`: Character for completed section
- `incomplete`: Character for incomplete section
- `renderThrottle`: Minimum time between renders
- `clear`: Whether to clear the bar on completion
- `showEta`: Show estimated time remaining
- `showPercent`: Show percentage completed
- `showCount`: Show count of items
**Methods:**
- `update(value)`: Update progress to a specific value
- `increment(value?)`: Increment progress by a value (default: 1)
- `complete()`: Mark the progress bar as complete
- `setColor(color)`: Set the color of the progress bar
## File Destination Module (`@push.rocks/smartlog/destination-file`)
This module provides a log destination that writes logs to a file.
### Classes
#### `SmartlogDestinationFile`
Writes logs to a file with timestamps.
```typescript
import { Smartlog } from '@push.rocks/smartlog';
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
const logger = new Smartlog({/*...*/});
const fileDestination = new SmartlogDestinationFile('/absolute/path/to/logfile.log');
logger.addLogDestination(fileDestination);
```
**Constructor Parameters:**
- `filePath`: Absolute path to the log file
## Local Destination Module (`@push.rocks/smartlog/destination-local`)
This module provides a log destination with colorful formatting for local development.
### Classes
#### `DestinationLocal`
Formats logs with colors and prefixes for better readability in the console.
```typescript
import { Smartlog } from '@push.rocks/smartlog';
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
const logger = new Smartlog({/*...*/});
const localDestination = new DestinationLocal();
logger.addLogDestination(localDestination);
```
**Methods:**
- `handleLog(logPackage)`: Handles a log package
- `newLine(lines?)`: Adds empty lines to the console
- `logReduced(text, repeatEveryTimes?)`: Logs only when the message changes
## DevTools Destination Module (`@push.rocks/smartlog/destination-devtools`)
This module provides a log destination that formats logs for browser developer tools.
### Classes
#### `SmartlogDestinationDevtools`
Formats logs with colors for browser developer tools.
```typescript
import { Smartlog } from '@push.rocks/smartlog';
import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
const logger = new Smartlog({/*...*/});
const devtoolsDestination = new SmartlogDestinationDevtools();
logger.addLogDestination(devtoolsDestination);
```
## ClickHouse Destination Module (`@push.rocks/smartlog/destination-clickhouse`)
This module provides a log destination that stores logs in a ClickHouse database.
### Classes
#### `SmartlogDestinationClickhouse`
Stores logs in a ClickHouse database for analytics and querying.
```typescript
import { Smartlog } from '@push.rocks/smartlog';
import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
const logger = new Smartlog({/*...*/});
const clickhouseDestination = await SmartlogDestinationClickhouse.createAndStart({
host: 'clickhouse.example.com',
port: 8123,
user: 'username',
password: 'password',
database: 'logs_db'
});
logger.addLogDestination(clickhouseDestination);
```
**Static Methods:**
- `createAndStart(options)`: Create and initialize a ClickHouse destination
**Methods:**
- `start()`: Initialize the connection to ClickHouse
- `handleLog(logPackage)`: Store a log in ClickHouse

View File

@ -1,5 +1,47 @@
# Changelog # Changelog
## 2025-05-20 - 3.1.8 - fix(devDependencies)
Update devDependencies for tstest and Node types
- Bump @git.zone/tstest from ^1.7.0 to ^1.9.0
- Bump @types/node from ^22.15.18 to ^22.15.20
## 2025-05-20 - 3.1.7 - fix(ts_destination_local)
Update debug log color: set textColor to 'pink' in DestinationLocal.
- Changed debug log text color from 'gray' to 'pink' for improved consistency in log output
## 2025-05-20 - 3.1.6 - fix(ts_destination_local)
Update debug prefix color in DestinationLocal: change from gray to pink for improved visibility.
- Adjusted the 'debug' log prefix color in classes.destinationlocal.ts to use 'pink' instead of 'gray'.
## 2025-05-20 - 3.1.5 - fix(core)
Maintain and verify project metadata and commit info consistency
- No code changes; confirming commit info files and documentation remain aligned
- Ensured consistent versioning across submodules and package metadata
## 2025-05-20 - 3.1.4 - fix(DestinationLocal)
Fix debug log rendering, add fallback for unknown log levels, and correct error prefix typo in local destination
- Added tests for debug and unknown log levels in DestinationLocal
- Refactored log string generation to use a fallback style for undefined levels
- Fixed typo: replaced non-existent 'errorPrefix' with 'error.prefix'
## 2025-05-19 - 3.1.3 - fix(documentation)
Update API reference and enhance README with detailed examples and usage instructions
- Added comprehensive API.md with reference details for core modules, interfaces, and interactive console features
- Updated README.md with improved installation steps, usage examples, and log group information
- Revised development hints to reflect environment detection and test file organization
## 2025-05-16 - 3.1.2 - fix(tests)
Update test imports and devDependencies to use @git.zone/tstest/tapbundle
- Changed import statements in test files from '@push.rocks/tapbundle' to '@git.zone/tstest/tapbundle'
- Updated devDependency '@git.zone/tstest' to version ^1.7.0 and removed dependency on '@push.rocks/tapbundle'
## 2025-05-15 - 3.1.1 - fix(source-interactive) ## 2025-05-15 - 3.1.1 - fix(source-interactive)
Fix import path in receiver tests and rename progress bar property for clarity; update SmartlogSourceOra getter for improved backward compatibility. Fix import path in receiver tests and rename progress bar property for clarity; update SmartlogSourceOra getter for improved backward compatibility.

View File

@ -1,6 +1,6 @@
{ {
"name": "@push.rocks/smartlog", "name": "@push.rocks/smartlog",
"version": "3.1.1", "version": "3.1.8",
"private": false, "private": false,
"description": "A minimalistic, distributed, and extensible logging tool supporting centralized log management.", "description": "A minimalistic, distributed, and extensible logging tool supporting centralized log management.",
"keywords": [ "keywords": [
@ -45,9 +45,8 @@
"@git.zone/tsbuild": "^2.5.1", "@git.zone/tsbuild": "^2.5.1",
"@git.zone/tsbundle": "^2.2.5", "@git.zone/tsbundle": "^2.2.5",
"@git.zone/tsrun": "^1.3.3", "@git.zone/tsrun": "^1.3.3",
"@git.zone/tstest": "^1.4.0", "@git.zone/tstest": "^1.9.0",
"@push.rocks/tapbundle": "^6.0.3", "@types/node": "^22.15.20"
"@types/node": "^22.15.18"
}, },
"dependencies": { "dependencies": {
"@api.global/typedrequest-interfaces": "^3.0.19", "@api.global/typedrequest-interfaces": "^3.0.19",

2118
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1 +1,53 @@
# SmartLog - Development Hints & Notes
This document contains notes and findings about the SmartLog library to help with development and understanding of the codebase.
## Key Components
- **Smartlog**: Main logger class that handles logging operations
- **LogRouter**: Routes logs to various destinations
- **LogGroup**: Groups related logs for better traceability
- **ConsoleLog**: Destination that logs to the console
- **ILogDestination**: Interface for implementing custom log destinations
## Core Concepts
- **Log Context**: Metadata about the environment (company, environment, runtime, etc.)
- **Log Levels**: 'silly', 'info', 'debug', 'note', 'ok', 'success', 'warn', 'error', 'lifecycle'
- **Log Types**: 'log', 'increment', 'gauge', 'error', 'success', 'value', 'finance', 'compliance'
- **Log Correlation**: Used to link related logs together (group, transaction, instance)
## Interactive Console Features
- **SmartlogSourceInteractive**: Creates interactive spinners for CLI applications
- **SmartlogProgressBar**: Creates progress bars for CLI applications
- Both automatically detect non-interactive environments and provide fallback behavior
## Environment Detection
The library uses feature detection to adapt to different environments:
- Checks for TTY capability
- Detects CI/CD environments (GitHub Actions, Jenkins, GitLab CI, Travis, CircleCI)
- Provides appropriate output based on the environment
## Available Destinations
- Console (built-in)
- File (ts_destination_file)
- Local (ts_destination_local)
- Clickhouse (ts_destination_clickhouse)
- Developer Tools (ts_destination_devtools)
- Receiver (ts_destination_receiver)
## Advanced Features
- **Increment Logging**: For metrics and counters
- **Console Capture**: Option to capture all console output through Smartlog
- **Custom Destinations**: Extend with custom log destinations
## Tests
Test files are organized by environment compatibility:
- *.both.ts: Tests for both browser and Node.js
- *.node.ts: Tests for Node.js only
- *.browser.ts: Tests for browser only

264
readme.md
View File

@ -1,103 +1,215 @@
# @push.rocks/smartlog # @push.rocks/smartlog
minimalistic distributed and extensible logging tool Minimalistic distributed and extensible logging tool for TypeScript and JavaScript applications.
## Install ## Install
You can install `@push.rocks/smartlog` using npm: Install `@push.rocks/smartlog` using pnpm (recommended), npm, or yarn:
```sh ```sh
# Using pnpm (recommended)
pnpm add @push.rocks/smartlog
# Using npm
npm install @push.rocks/smartlog --save npm install @push.rocks/smartlog --save
# Using yarn
yarn add @push.rocks/smartlog
``` ```
Ensure that you have TypeScript and node.js installed in your development environment, as this module is intended to be used with TypeScript. Ensure you have TypeScript and Node.js installed for TypeScript projects.
## Package Exports
The package provides the following exports:
```javascript
// Main module
import { Smartlog, LogGroup, ConsoleLog } from '@push.rocks/smartlog';
// Type definitions and interfaces
import { ILogPackage, ILogDestination, TLogLevel } from '@push.rocks/smartlog/interfaces';
// Interactive console features (spinners, progress bars)
import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
// Context management
import { ... } from '@push.rocks/smartlog/context';
// Log destinations
import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
// Receiver functionality
import { SmartlogReceiver } from '@push.rocks/smartlog/receiver';
```
## Usage ## Usage
`@push.rocks/smartlog` is a flexible and extensible logging tool designed to provide a minimalistic yet powerful logging solution across different environments, making it especially useful in distributed systems. This documentation aims to guide you through its capabilities, setup, and how to integrate it seamlessly into your TypeScript projects. `@push.rocks/smartlog` is a flexible, extensible logging tool designed for distributed systems. It provides a consistent logging interface across different environments while being lightweight and customizable.
### Creating a Logger Instance ### Creating a Logger Instance
Start by importing `Smartlog` and create a logger instance by providing a context that describes your logging environment: Start by importing `Smartlog` and create a logger instance:
```typescript ```typescript
import { Smartlog } from '@push.rocks/smartlog'; import { Smartlog } from '@push.rocks/smartlog';
const logger = new Smartlog({ const logger = new Smartlog({
logContext: { logContext: {
company: 'My awesome company', company: 'My Company',
companyunit: 'my awesome cloud team', companyunit: 'Cloud Team',
containerName: 'awesome-container', containerName: 'api-service',
environment: 'kubernetes-production', environment: 'production', // 'local', 'test', 'staging', 'production'
runtime: 'node', runtime: 'node', // 'node', 'chrome', 'rust', 'deno', 'cloudflare_workers'
zone: 'zone x', zone: 'us-west',
}, },
minimumLogLevel: 'info', // Optional, defaults to 'silly'
}); });
// Enable console output
logger.enableConsole();
``` ```
This context enriches your logs with valuable information, making them easier to filter and analyze in a distributed system. The context enriches logs with valuable information for filtering and analysis across distributed systems.
### Logging Messages ### Logging Messages
Logging is straightforward; you can log messages at various levels such as `info`, `warn`, `error`, `silly`, etc.:
```typescript ```typescript
logger.log('info', 'This is an info message'); // Basic logging
logger.log('error', 'This is an error message with details', { errorCode: 123 }); logger.log('info', 'User authenticated successfully');
logger.log('error', 'Database connection failed', { errorCode: 'DB_CONN_ERR', retryCount: 3 });
logger.log('warn', 'Rate limit approaching', { currentRate: 95, limit: 100 });
// Log levels: 'silly', 'info', 'debug', 'note', 'ok', 'success', 'warn', 'error', 'lifecycle'
``` ```
The logging method accepts additional data as the third parameter, allowing you to attach more context to each log message, which is immensely useful for debugging. The third parameter accepts any additional data to attach to the log entry.
### Using the Default Logger ### Default Logger
For convenience, `@push.rocks/smartlog` provides a default logger that you can use out of the box: For simple cases, use the built-in default logger:
```typescript ```typescript
import { defaultLogger } from '@push.rocks/smartlog'; import { defaultLogger } from '@push.rocks/smartlog';
defaultLogger.log('warn', 'This is a warning message using the default logger'); defaultLogger.log('info', 'Application started');
``` ```
This is particularly helpful for simple applications or for initial project setup. ### Log Groups
Group related logs for better traceability:
```typescript
// Create a log group with optional transaction ID
const requestGroup = logger.createLogGroup('tx-123456');
// Logs within this group will be correlated
requestGroup.log('info', 'Processing payment request');
requestGroup.log('debug', 'Validating payment details');
requestGroup.log('success', 'Payment processed successfully');
```
### Custom Log Destinations
Extend logging capabilities by adding custom destinations:
```typescript
import { Smartlog, ILogDestination } from '@push.rocks/smartlog';
class DatabaseLogDestination implements ILogDestination {
async handleLog(logPackage) {
// Store log in database
await db.logs.insert({
timestamp: new Date(logPackage.timestamp),
level: logPackage.level,
message: logPackage.message,
data: logPackage.data,
context: logPackage.context
});
}
}
// Add the custom destination to your logger
logger.addLogDestination(new DatabaseLogDestination());
```
### Built-in Destinations
SmartLog comes with several built-in destinations for various logging needs:
```typescript
// Log to a file
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
logger.addLogDestination(new SmartlogDestinationFile('/path/to/logfile.log'));
// Colorful local console logging
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
logger.addLogDestination(new DestinationLocal());
// Browser DevTools with colored formatting
import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
logger.addLogDestination(new SmartlogDestinationDevtools());
// ClickHouse database logging
import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
const clickhouse = await SmartlogDestinationClickhouse.createAndStart({
host: 'clickhouse.example.com',
port: 8123,
user: 'username',
password: 'password',
database: 'logs_db'
});
logger.addLogDestination(clickhouse);
// Remote receiver logging
import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
logger.addLogDestination(new SmartlogDestinationReceiver({
endpoint: 'https://logs.example.com/api/logs'
}));
```
### Interactive Console Features ### Interactive Console Features
Smartlog provides interactive console features through the `@push.rocks/smartlog/source-interactive` module: For CLI applications, use the interactive console features:
```typescript
import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
```
#### Spinners #### Spinners
Use spinners to show progress for operations:
```typescript ```typescript
import { SmartlogSourceInteractive } from '@push.rocks/smartlog/source-interactive';
const spinner = new SmartlogSourceInteractive(); const spinner = new SmartlogSourceInteractive();
// Start a spinner with text
spinner.text('Loading data...'); spinner.text('Loading data...');
// Later, when the operation completes: // Customize appearance
spinner.setSpinnerStyle('dots'); // 'dots', 'line', 'star', 'simple'
spinner.setColor('blue'); // 'red', 'green', 'yellow', 'blue', etc.
spinner.setSpeed(80); // Animation speed in milliseconds
// Update spinner status
spinner.text('Processing records...');
// Complete with success or failure
spinner.finishSuccess('Data loaded successfully!'); spinner.finishSuccess('Data loaded successfully!');
// Or if it fails: spinner.finishFail('Failed to load data!');
spinner.finishFail('Failed to load data');
// You can chain operations: // Chain operations
spinner.text('Connecting to server'); spinner.text('Connecting to server')
spinner.successAndNext('Fetching records'); .successAndNext('Fetching records')
spinner.successAndNext('Processing data'); .successAndNext('Processing data')
spinner.finishSuccess('All done!'); .finishSuccess('All done!');
// Customize appearance:
spinner.setSpinnerStyle('line'); // 'dots', 'line', 'star', or 'simple'
spinner.setColor('green'); // 'red', 'green', 'yellow', 'blue', etc.
spinner.setSpeed(100); // Animation speed in milliseconds
``` ```
#### Progress Bars #### Progress Bars
Create progress bars for tracking operation progress:
```typescript ```typescript
import { SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
const progressBar = new SmartlogProgressBar({ const progressBar = new SmartlogProgressBar({
total: 100, // Total number of items total: 100, // Total number of items
width: 40, // Width of the progress bar width: 40, // Width of the progress bar
@ -109,72 +221,64 @@ const progressBar = new SmartlogProgressBar({
}); });
// Update progress // Update progress
progressBar.update(50); // Set to 50% progress progressBar.update(25); // Set to 25% progress
// Or increment // Increment progress
progressBar.increment(10); // Increase by 10 units progressBar.increment(5); // Increase by 5 units
// Change color // Change color
progressBar.setColor('blue'); progressBar.setColor('blue');
// Complete the progress bar // Complete the progress bar
progressBar.update(100); // or progressBar.complete(); progressBar.complete();
``` ```
#### Non-Interactive Environments #### Non-Interactive Environments
Both spinners and progress bars automatically detect non-interactive environments (CI/CD, piped output, non-TTY) and provide fallback text-based output: Both spinners and progress bars automatically detect non-interactive environments (CI/CD, piped output) and fallback to plain text logging:
``` ```
[Loading] Loading data... [Loading] Connecting to server
[Success] Connected to server
[Loading] Fetching records
Progress: 50% (50/100) Progress: 50% (50/100)
Progress: 100% (100/100) Progress: 100% (100/100)
[Success] Data loaded successfully! [Success] Fetching complete
``` ```
### Extending With Log Destinations ## Advanced Usage
One of the core strengths of `@push.rocks/smartlog` is its ability to work with multiple log destinations, enabling you to log messages not just to the console but also to external logging services or custom destinations. ### Capturing All Console Output
To add a log destination, you create a class that implements the `ILogDestination` interface and then add it to the logger: Capture all `console.log` and `console.error` output through Smartlog:
```typescript ```typescript
import { Smartlog, ILogDestination } from '@push.rocks/smartlog'; logger.enableConsole({ captureAll: true });
class MyCustomLogDestination implements ILogDestination {
async handleLog(logPackage) {
// Implement your custom logging logic here
console.log(`Custom log: ${logPackage.message}`);
}
}
const logger = new Smartlog({
logContext: {
/* your context */
},
});
logger.addLogDestination(new MyCustomLogDestination());
``` ```
After adding your custom log destination(s), every log message sent through `Smartlog` will also be routed to them according to their implementation. ### Increment Logging
### Integration with Logging Services For metrics and counters:
`@push.rocks/smartlog` is designed to be extensible; you can integrate it with various logging services like Scalyr, Elasticsearch, LogDNA, etc., by developing or using existing log destinations conforming to those services. ```typescript
logger.increment('info', 'api_requests', { endpoint: '/users' });
```
Check the npm registry or GitHub for community-contributed log destinations that can seamlessly integrate `@push.rocks/smartlog` into your preferred logging infrastructure. ### Log Correlation
### Advanced Usage Correlate logs across services with correlation IDs:
- **Log Groups**: You can use log groups to associate related log messages, which is especially handy for tracking logs across distributed systems. ```typescript
- **Custom Log Levels**: Beyond the standard log levels, you can define custom log levels that suit your project needs. logger.log('info', 'Request received', { userId: 'user-123' }, {
- **Dynamic Log Contexts**: The log context can be dynamically adjusted to reflect different stages or aspects of your application logic. id: 'req-abc-123',
type: 'service',
transaction: 'tx-payment-456'
});
```
### Conclusion ## API Documentation
`@push.rocks/smartlog` empowers you to implement a robust logging solution tailored to your needs with minimal effort. Its design promotes clarity, flexibility, and integration ease, making it an excellent choice for projects of any scale. For detailed API documentation, see the [API.md](API.md) file.
Remember to refer to the official documentation and the type definitions for detailed information on all available methods and configurations. Happy logging!
## License and Legal Information ## License and Legal Information

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartlog from '../ts/index.js'; import * as smartlog from '../ts/index.js';
let testConsoleLog: smartlog.ConsoleLog; let testConsoleLog: smartlog.ConsoleLog;

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartlogContext from '../ts_context/index.js'; import * as smartlogContext from '../ts_context/index.js';
tap.test('should correctly export strings from context module', async () => { tap.test('should correctly export strings from context module', async () => {

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogDestinationClickhouse } from '../ts_destination_clickhouse/index.js'; import { SmartlogDestinationClickhouse } from '../ts_destination_clickhouse/index.js';
import * as smartclickhouse from '@push.rocks/smartclickhouse'; import * as smartclickhouse from '@push.rocks/smartclickhouse';

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogDestinationDevtools } from '../ts_destination_devtools/index.js'; import { SmartlogDestinationDevtools } from '../ts_destination_devtools/index.js';
export const run = async function() { export const run = async function() {

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogDestinationDevtools } from '../ts_destination_devtools/index.js'; import { SmartlogDestinationDevtools } from '../ts_destination_devtools/index.js';
// Test we can create a destination instance // Test we can create a destination instance

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogDestinationFile } from '../ts_destination_file/index.js'; import { SmartlogDestinationFile } from '../ts_destination_file/index.js';
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import { DestinationLocal } from '../ts_destination_local/index.js'; import { DestinationLocal } from '../ts_destination_local/index.js';
import * as smartlogInterfaces from '../ts_interfaces/index.js'; import * as smartlogInterfaces from '../ts_interfaces/index.js';
@ -92,5 +92,23 @@ tap.test('should create new line(s)', async () => {
// Multiple lines // Multiple lines
testDestination.newLine(3); testDestination.newLine(3);
}); });
// Test debug level rendering and fallback for unknown levels
tap.test('should handle debug and unknown log levels', async () => {
testDestination = new DestinationLocal();
let out = '';
const originalLog = console.log;
console.log = (msg: string) => { out += msg; };
// debug level should render message correctly
await testDestination.handleLog(createMockLogPackage('debug', 'debug 🎉'));
expect(out).toContain('debug 🎉');
// fallback for unknown level should still render message
out = '';
await testDestination.handleLog(createMockLogPackage('verbose' as any, 'verbose ⚠️'));
expect(out).toContain('verbose ⚠️');
console.log = originalLog;
});
export default tap.start(); export default tap.start();

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogDestinationReceiver } from '../ts_destination_receiver/index.js'; import { SmartlogDestinationReceiver } from '../ts_destination_receiver/index.js';
import { Smartlog } from '../ts/index.js'; import { Smartlog } from '../ts/index.js';
import * as smartlogInterfaces from '../ts_interfaces/index.js'; import * as smartlogInterfaces from '../ts_interfaces/index.js';

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogSourceInteractive, SmartlogProgressBar } from '../ts_source_interactive/index.js'; import { SmartlogSourceInteractive, SmartlogProgressBar } from '../ts_source_interactive/index.js';
// Test instances // Test instances

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogReceiver } from '../ts_receiver/index.js'; import { SmartlogReceiver } from '../ts_receiver/index.js';
import { Smartlog } from '../dist_ts/index.js'; import { Smartlog } from '../dist_ts/index.js';
import * as smartlogInterfaces from '../ts_interfaces/index.js'; import * as smartlogInterfaces from '../ts_interfaces/index.js';

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogSourceInteractive, SmartlogProgressBar, SmartlogSourceOra } from '../ts_source_interactive/index.js'; import { SmartlogSourceInteractive, SmartlogProgressBar, SmartlogSourceOra } from '../ts_source_interactive/index.js';
// Test spinner functionality // Test spinner functionality

View File

@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartlog from '../ts/index.js'; import * as smartlog from '../ts/index.js';
let testConsoleLog: smartlog.ConsoleLog; let testConsoleLog: smartlog.ConsoleLog;

View File

@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartlog', name: '@push.rocks/smartlog',
version: '3.1.1', version: '3.1.8',
description: 'A minimalistic, distributed, and extensible logging tool supporting centralized log management.' description: 'A minimalistic, distributed, and extensible logging tool supporting centralized log management.'
} }

View File

@ -61,19 +61,22 @@ export class DestinationLocal implements ILogDestination {
// default logging // default logging
private logToConsole(logPackageArg: ILogPackage) { private logToConsole(logPackageArg: ILogPackage) {
let logString: string;
try { try {
logString = const style = this.localBl[logPackageArg.level] ?? this.localBl.info;
this.localBl[logPackageArg.level].prefix + const logString =
style.prefix +
plugins.consolecolor.coloredString( plugins.consolecolor.coloredString(
logPackageArg.message, logPackageArg.message,
this.localBl[logPackageArg.level].textColor style.textColor
); );
console.log(logString); console.log(logString);
return true; return true;
} catch (error) { } catch (error) {
// typo fix: use the defined error.prefix, not a non-existent errorPrefix
console.log( console.log(
this.localBl.errorPrefix + 'You seem to have tried logging something strange' + error this.localBl.error.prefix +
'You seem to have tried logging something strange ' +
error
); );
return false; return false;
} }
@ -89,6 +92,10 @@ export class DestinationLocal implements ILogDestination {
prefix: plugins.consolecolor.coloredString(' silly ', 'white', 'blue') + ' ', prefix: plugins.consolecolor.coloredString(' silly ', 'white', 'blue') + ' ',
textColor: 'blue', textColor: 'blue',
}, },
debug: {
prefix: plugins.consolecolor.coloredString(' debug ', 'pink', 'black') + ' ',
textColor: 'pink',
},
error: { error: {
prefix: prefix:
plugins.consolecolor.coloredString(' ', 'red', 'red') + plugins.consolecolor.coloredString(' ', 'red', 'red') +