Compare commits

...

20 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
75783b0e87 3.1.1
Some checks failed
Default (tags) / security (push) Successful in 45s
Default (tags) / test (push) Failing after 1m6s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-15 20:00:38 +00:00
13e1582732 fix(source-interactive): Fix import path in receiver tests and rename progress bar property for clarity; update SmartlogSourceOra getter for improved backward compatibility. 2025-05-15 20:00:38 +00:00
7e2f076b35 3.1.0
Some checks failed
Default (tags) / security (push) Successful in 38s
Default (tags) / test (push) Failing after 1m6s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-15 19:53:29 +00:00
7e8a404fcf feat(interactive): Add interactive console features and refactor spinner module by renaming source-ora to source-interactive and removing ora dependency 2025-05-15 19:53:29 +00:00
09da3a1e2d 3.0.9
Some checks failed
Default (tags) / security (push) Successful in 31s
Default (tags) / test (push) Failing after 1m0s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-05-12 10:20:16 +00:00
f542596eae fix(test/destination-devtools.browser): Simplify DevTools browser tests by removing redundant styled log assertions. 2025-05-12 10:20:16 +00:00
26 changed files with 2395 additions and 1662 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,69 @@
# 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)
Fix import path in receiver tests and rename progress bar property for clarity; update SmartlogSourceOra getter for improved backward compatibility.
- Changed test file import from '../ts/index.js' to '../dist_ts/index.js' in test.receiver.node.ts to resolve module path issues
- Renamed property 'complete' to 'completeChar' in SmartlogProgressBar and updated its usage accordingly
- Modified SmartlogSourceOra getter to use public methods for starting and stopping the spinner, ensuring backward compatibility
## 2025-05-15 - 3.1.0 - feat(interactive)
Add interactive console features and refactor spinner module by renaming source-ora to source-interactive and removing ora dependency
- Renamed source-ora module to source-interactive and updated package.json exports
- Removed ora dependency in favor of a custom spinner implementation
- Added new progress bar functionality with configurable options including ETA, percentage, and color
- Updated tests and documentation (README and plan) to reflect the new interactive features
- Bumped dependency versions in package.json and improved test script configuration
## 2025-05-12 - 3.0.9 - fix(test/destination-devtools.browser)
Simplify DevTools browser tests by removing redundant styled log assertions.
- Removed detailed log styling tests to streamline the browser test suite.
- Retained a basic test to verify DevTools destination instance creation.
## 2025-05-11 - 3.0.8 - fix(ci)
Update CI workflows, build scripts, and export configuration

View File

@ -1,6 +1,6 @@
{
"name": "@push.rocks/smartlog",
"version": "3.0.8",
"version": "3.1.8",
"private": false,
"description": "A minimalistic, distributed, and extensible logging tool supporting centralized log management.",
"keywords": [
@ -25,7 +25,7 @@
},
"./context": "./dist_ts_context/index.js",
"./interfaces": "./dist_ts_interfaces/index.js",
"./source-ora": "./dist_ts_source_ora/index.js",
"./source-interactive": "./dist_ts_source_interactive/index.js",
"./destination-clickhouse": "./dist_ts_destination_clickhouse/index.js",
"./destination-devtools": "./dist_ts_destination_devtools/index.js",
"./destination-file": "./dist_ts_destination_file/index.js",
@ -36,18 +36,17 @@
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest test/)",
"test": "(tstest test/**/*.ts --verbose)",
"build": "(tsbuild tsfolders --allowimplicitany && tsbundle npm)",
"format": "(gitzone format)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@git.zone/tsbuild": "^2.3.2",
"@git.zone/tsbuild": "^2.5.1",
"@git.zone/tsbundle": "^2.2.5",
"@git.zone/tsrun": "^1.3.3",
"@git.zone/tstest": "^1.0.96",
"@push.rocks/tapbundle": "^6.0.3",
"@types/node": "^22.15.17"
"@git.zone/tstest": "^1.9.0",
"@types/node": "^22.15.20"
},
"dependencies": {
"@api.global/typedrequest-interfaces": "^3.0.19",
@ -59,8 +58,7 @@
"@push.rocks/smartpromise": "^4.2.3",
"@push.rocks/smarttime": "^4.1.1",
"@push.rocks/webrequest": "^3.0.37",
"@tsclass/tsclass": "^9.2.0",
"ora": "^8.2.0"
"@tsclass/tsclass": "^9.2.0"
},
"files": [
"ts/**/*",

2272
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

266
readme.md
View File

@ -1,108 +1,284 @@
# @push.rocks/smartlog
minimalistic distributed and extensible logging tool
Minimalistic distributed and extensible logging tool for TypeScript and JavaScript applications.
## Install
You can install `@push.rocks/smartlog` using npm:
Install `@push.rocks/smartlog` using pnpm (recommended), npm, or yarn:
```sh
# Using pnpm (recommended)
pnpm add @push.rocks/smartlog
# Using npm
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
`@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
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
import { Smartlog } from '@push.rocks/smartlog';
const logger = new Smartlog({
logContext: {
company: 'My awesome company',
companyunit: 'my awesome cloud team',
containerName: 'awesome-container',
environment: 'kubernetes-production',
runtime: 'node',
zone: 'zone x',
company: 'My Company',
companyunit: 'Cloud Team',
containerName: 'api-service',
environment: 'production', // 'local', 'test', 'staging', 'production'
runtime: 'node', // 'node', 'chrome', 'rust', 'deno', 'cloudflare_workers'
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 is straightforward; you can log messages at various levels such as `info`, `warn`, `error`, `silly`, etc.:
```typescript
logger.log('info', 'This is an info message');
logger.log('error', 'This is an error message with details', { errorCode: 123 });
// Basic logging
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
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
### Extending With Log Destinations
Group related logs for better traceability:
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.
```typescript
// Create a log group with optional transaction ID
const requestGroup = logger.createLogGroup('tx-123456');
To add a log destination, you create a class that implements the `ILogDestination` interface and then add it to the logger:
// 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 MyCustomLogDestination implements ILogDestination {
class DatabaseLogDestination implements ILogDestination {
async handleLog(logPackage) {
// Implement your custom logging logic here
console.log(`Custom log: ${logPackage.message}`);
// 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
});
}
}
const logger = new Smartlog({
logContext: {
/* your context */
},
});
logger.addLogDestination(new MyCustomLogDestination());
// Add the custom destination to your logger
logger.addLogDestination(new DatabaseLogDestination());
```
After adding your custom log destination(s), every log message sent through `Smartlog` will also be routed to them according to their implementation.
### Built-in Destinations
### Integration with Logging Services
SmartLog comes with several built-in destinations for various logging needs:
`@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
// Log to a file
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
logger.addLogDestination(new SmartlogDestinationFile('/path/to/logfile.log'));
Check the npm registry or GitHub for community-contributed log destinations that can seamlessly integrate `@push.rocks/smartlog` into your preferred logging infrastructure.
// Colorful local console logging
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
logger.addLogDestination(new DestinationLocal());
### Advanced Usage
// Browser DevTools with colored formatting
import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
logger.addLogDestination(new SmartlogDestinationDevtools());
- **Log Groups**: You can use log groups to associate related log messages, which is especially handy for tracking logs across distributed systems.
- **Custom Log Levels**: Beyond the standard log levels, you can define custom log levels that suit your project needs.
- **Dynamic Log Contexts**: The log context can be dynamically adjusted to reflect different stages or aspects of your application logic.
// 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);
### Conclusion
// Remote receiver logging
import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
logger.addLogDestination(new SmartlogDestinationReceiver({
endpoint: 'https://logs.example.com/api/logs'
}));
```
`@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.
### Interactive Console Features
Remember to refer to the official documentation and the type definitions for detailed information on all available methods and configurations. Happy logging!
For CLI applications, use the interactive console features:
```typescript
import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
```
#### Spinners
```typescript
const spinner = new SmartlogSourceInteractive();
// Start a spinner with text
spinner.text('Loading data...');
// 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.finishFail('Failed to load data!');
// Chain operations
spinner.text('Connecting to server')
.successAndNext('Fetching records')
.successAndNext('Processing data')
.finishSuccess('All done!');
```
#### Progress Bars
```typescript
const progressBar = new SmartlogProgressBar({
total: 100, // Total number of items
width: 40, // Width of the progress bar
complete: '█', // Character for completed section
incomplete: '░', // Character for incomplete section
showEta: true, // Show estimated time remaining
showPercent: true, // Show percentage
showCount: true // Show count (e.g., "50/100")
});
// Update progress
progressBar.update(25); // Set to 25% progress
// Increment progress
progressBar.increment(5); // Increase by 5 units
// Change color
progressBar.setColor('blue');
// Complete the progress bar
progressBar.complete();
```
#### Non-Interactive Environments
Both spinners and progress bars automatically detect non-interactive environments (CI/CD, piped output) and fallback to plain text logging:
```
[Loading] Connecting to server
[Success] Connected to server
[Loading] Fetching records
Progress: 50% (50/100)
Progress: 100% (100/100)
[Success] Fetching complete
```
## Advanced Usage
### Capturing All Console Output
Capture all `console.log` and `console.error` output through Smartlog:
```typescript
logger.enableConsole({ captureAll: true });
```
### Increment Logging
For metrics and counters:
```typescript
logger.increment('info', 'api_requests', { endpoint: '/users' });
```
### Log Correlation
Correlate logs across services with correlation IDs:
```typescript
logger.log('info', 'Request received', { userId: 'user-123' }, {
id: 'req-abc-123',
type: 'service',
transaction: 'tx-payment-456'
});
```
## API Documentation
For detailed API documentation, see the [API.md](API.md) file.
## License and Legal Information
@ -121,4 +297,4 @@ Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
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.
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.

View File

@ -0,0 +1,101 @@
# Smartlog Interactive Console Features Plan
## Overview
This document outlines the plan for enhancing the console output capabilities of `@push.rocks/smartlog` by creating a comprehensive interactive console module. This involves renaming the current `ts_source_ora` module to `ts_source_interactive`, implementing our own spinner functionality (removing the ora dependency), and adding new features like progress bars and other interactive elements.
## Implementation Steps
### 1. Rename and Restructure
- Rename directory from `ts_source_ora` to `ts_source_interactive`
- Update all imports, exports, and references
- Update package.json exports to reflect new module name
- Maintain backward compatibility through proper export paths
### 2. Custom Spinner Implementation
- Create a native spinner implementation to replace ora dependency
- Implement spinner frames and animation timing
- Maintain API compatibility with current spinner methods:
- `text(textArg)` - Set text and start spinner
- `stop()` - Stop the spinner
- `finishSuccess(textArg?)` - Mark as succeeded
- `finishFail(textArg?)` - Mark as failed
- `successAndNext(textArg)` - Success and start new spinner
- `failAndNext(textArg)` - Fail and start new spinner
- Add spinner customization options (speed, frames, colors)
### 3. Progress Bar Implementation
- Create a progress bar component with the following features:
- Configurable width and style
- Percentage display
- ETA calculation
- Current/total value display
- Custom formatting
- Theming support
- Methods for incrementing and updating
### 4. Additional Interactive Features
- Add indeterminate progress indicator
- Add multi-line status display
- Add table formatting for structured data
- Add interactive prompts/confirmations
### 5. Testing
- Update existing tests to work with new implementation
- Add tests for new progress bar functionality
- Add tests for additional interactive features
- Ensure consistent behavior across platforms
### 6. Documentation
- Update README with examples of new features
- Add API documentation for all new methods
- Include usage examples
## Implementation Details
### Progress Bar API
```typescript
// Creating a progress bar
const progressBar = new SmartlogProgressBar({
total: 100,
width: 40,
complete: '=',
incomplete: ' ',
renderThrottle: 100, // ms
clearOnComplete: false,
showEta: true
});
// Updating a progress bar
progressBar.update(50); // Update to 50%
progressBar.increment(10); // Increment by 10
progressBar.complete(); // Mark as complete
```
### Spinner API (maintains compatibility)
```typescript
// Current API (to be maintained)
const spinner = new SmartlogSourceInteractive();
spinner.text('Loading data');
spinner.finishSuccess('Data loaded successfully');
// New additions
spinner.setSpinnerStyle('dots'); // Change spinner style
spinner.setColor('green'); // Change color
```
## Benefits
- Remove external dependency (ora) for better control and smaller bundle size
- Provide more interactive console features for improved user experience
- Maintain consistent API styling across all smartlog modules
- Improve testability with custom implementation
- Enable more advanced terminal interactions

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';
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';
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 * as smartclickhouse from '@push.rocks/smartclickhouse';

View File

@ -1,117 +1,13 @@
import { expect, tap } from '@push.rocks/tapbundle';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogDestinationDevtools } from '../ts_destination_devtools/index.js';
import * as smartlogInterfaces from '../ts_interfaces/index.js';
let testDestination: SmartlogDestinationDevtools;
let originalConsoleLog: any;
let consoleLogCalls: any[] = [];
// Helper to create log package
const createMockLogPackage = (level: smartlogInterfaces.TLogLevel, message: string): smartlogInterfaces.ILogPackage => {
return {
timestamp: Date.now(),
type: 'log',
level,
message,
context: {
environment: 'test',
runtime: 'chrome'
},
correlation: {
id: '123',
type: 'none'
}
};
export const run = async function() {
tap.test('should create a DevTools destination instance in browser', async () => {
const devtoolsDestination = new SmartlogDestinationDevtools();
expect(devtoolsDestination).toBeTruthy();
});
return await tap.start();
};
// Tests
tap.test('should setup test environment', async () => {
// Save original console.log
originalConsoleLog = console.log;
// Replace with mock
console.log = (...args: any[]) => {
consoleLogCalls.push(args);
// Don't call original to avoid polluting test output
};
});
tap.test('should create a devtools destination instance', async () => {
testDestination = new SmartlogDestinationDevtools();
expect(testDestination).toBeTruthy();
});
tap.test('should log error level messages with appropriate styling', async () => {
consoleLogCalls = [];
const logPackage = createMockLogPackage('error', 'Test error message');
await testDestination.handleLog(logPackage);
expect(consoleLogCalls.length).toEqual(1);
expect(consoleLogCalls[0][0]).toContain('Error:');
expect(consoleLogCalls[0][1]).toContain('background:#000000;color:#800000;');
expect(consoleLogCalls[0][2]).toContain('Test error message');
});
tap.test('should log info level messages with appropriate styling', async () => {
consoleLogCalls = [];
const logPackage = createMockLogPackage('info', 'Test info message');
await testDestination.handleLog(logPackage);
expect(consoleLogCalls.length).toEqual(1);
expect(consoleLogCalls[0][0]).toContain('Info:');
expect(consoleLogCalls[0][1]).toContain('background:#EC407A;color:#ffffff;');
expect(consoleLogCalls[0][2]).toContain('Test info message');
});
tap.test('should log ok level messages with appropriate styling', async () => {
consoleLogCalls = [];
const logPackage = createMockLogPackage('ok', 'Test ok message');
await testDestination.handleLog(logPackage);
expect(consoleLogCalls.length).toEqual(1);
expect(consoleLogCalls[0][0]).toContain('OK:');
expect(consoleLogCalls[0][2]).toContain('Test ok message');
});
tap.test('should log success level messages with appropriate styling', async () => {
consoleLogCalls = [];
const logPackage = createMockLogPackage('success', 'Test success message');
await testDestination.handleLog(logPackage);
expect(consoleLogCalls.length).toEqual(1);
expect(consoleLogCalls[0][0]).toContain('Success:');
expect(consoleLogCalls[0][2]).toContain('Test success message');
});
tap.test('should log warn level messages with appropriate styling', async () => {
consoleLogCalls = [];
const logPackage = createMockLogPackage('warn', 'Test warning message');
await testDestination.handleLog(logPackage);
expect(consoleLogCalls.length).toEqual(1);
expect(consoleLogCalls[0][0]).toContain('Warn:');
expect(consoleLogCalls[0][2]).toContain('Test warning message');
});
tap.test('should log note level messages with appropriate styling', async () => {
consoleLogCalls = [];
const logPackage = createMockLogPackage('note', 'Test note message');
await testDestination.handleLog(logPackage);
expect(consoleLogCalls.length).toEqual(1);
expect(consoleLogCalls[0][0]).toContain('Note:');
expect(consoleLogCalls[0][2]).toContain('Test note message');
});
tap.test('should clean up test environment', async () => {
// Restore the original console.log
console.log = originalConsoleLog;
});
export default tap.start();
export default run();

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';
// 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 * as fs from 'fs';
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 * as smartlogInterfaces from '../ts_interfaces/index.js';
@ -92,5 +92,23 @@ tap.test('should create new line(s)', async () => {
// Multiple lines
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();

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 { Smartlog } from '../ts/index.js';
import * as smartlogInterfaces from '../ts_interfaces/index.js';

View File

@ -0,0 +1,64 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogSourceInteractive, SmartlogProgressBar } from '../ts_source_interactive/index.js';
// Test instances
let testSpinner: SmartlogSourceInteractive;
let testProgressBar: SmartlogProgressBar;
// Original state for restoration
const originalState = {
stdoutTTY: process.stdout.isTTY,
consoleLog: console.log
};
// Log tracking
const logs: string[] = [];
tap.test('should handle non-interactive mode correctly', async (toolsArg) => {
// Setup non-interactive mode
process.stdout.isTTY = false;
console.log = (...args: any[]) => {
logs.push(args.join(' '));
};
// Test spinner creation
testSpinner = new SmartlogSourceInteractive();
expect(testSpinner).toBeTruthy();
// Test spinner text
logs.length = 0;
testSpinner.text('Loading data');
expect(logs.length).toBeGreaterThan(0);
expect(logs[0]).toContain('[Loading]');
expect(logs[0]).toContain('Loading data');
// Test spinner success
logs.length = 0;
testSpinner.finishSuccess('Task completed');
expect(logs.length).toBeGreaterThan(0);
expect(logs[0]).toContain('[Success]');
expect(logs[0]).toContain('Task completed');
// Test progress bar
testProgressBar = new SmartlogProgressBar({ total: 100 });
expect(testProgressBar).toBeTruthy();
// Test progress updates
logs.length = 0;
testProgressBar.update(10);
testProgressBar.update(50);
testProgressBar.update(100);
expect(logs.length).toBeGreaterThan(0);
const progressLogs = logs.join(' ');
expect(progressLogs).toContain('10%');
expect(progressLogs).toContain('50%');
expect(progressLogs).toContain('100%');
// Cleanup
testSpinner.stop();
console.log = originalState.consoleLog;
process.stdout.isTTY = originalState.stdoutTTY;
});
export default tap.start();

View File

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

View File

@ -0,0 +1,190 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartlogSourceInteractive, SmartlogProgressBar, SmartlogSourceOra } from '../ts_source_interactive/index.js';
// Test spinner functionality
let testSpinner: SmartlogSourceInteractive;
// Helper function to clean up spinners after each test
const cleanupSpinner = (spinner: SmartlogSourceInteractive) => {
if (spinner.isStarted()) {
spinner.stop();
}
};
tap.test('should create a SmartlogSourceInteractive instance', async () => {
testSpinner = new SmartlogSourceInteractive();
testSpinner.setSpeed(10); // Set fast animation speed for tests
expect(testSpinner).toBeTruthy();
expect(testSpinner.isStarted()).toBeFalse();
});
tap.test('should set text and start spinner', async () => {
const testText = 'Testing spinner';
testSpinner.text(testText);
expect(testSpinner.isStarted()).toBeTrue();
cleanupSpinner(testSpinner);
});
tap.test('should update text', async () => {
const newText = 'Updated text';
testSpinner.text(newText);
expect(testSpinner.isStarted()).toBeTrue();
cleanupSpinner(testSpinner);
});
tap.test('should stop spinner', async () => {
testSpinner.stop();
// We can't easily test the visual state, but we can verify it doesn't throw errors
});
tap.test('should finish with success', async () => {
testSpinner = new SmartlogSourceInteractive();
testSpinner.text('Starting again');
const successText = 'Operation successful';
testSpinner.finishSuccess(successText);
expect(testSpinner.isStarted()).toBeFalse();
});
tap.test('should finish with failure', async () => {
testSpinner = new SmartlogSourceInteractive();
testSpinner.text('Starting again');
const failText = 'Operation failed';
testSpinner.finishFail(failText);
expect(testSpinner.isStarted()).toBeFalse();
});
tap.test('should handle success and next', async () => {
testSpinner = new SmartlogSourceInteractive();
testSpinner.setSpeed(10); // Fast animation
testSpinner.text('Starting again');
const nextText = 'Next operation';
testSpinner.successAndNext(nextText);
expect(testSpinner.isStarted()).toBeTrue();
cleanupSpinner(testSpinner);
});
tap.test('should handle fail and next', async () => {
testSpinner = new SmartlogSourceInteractive();
testSpinner.setSpeed(10); // Fast animation
testSpinner.text('Starting again');
const nextText = 'Next operation after failure';
testSpinner.failAndNext(nextText);
expect(testSpinner.isStarted()).toBeTrue();
cleanupSpinner(testSpinner);
});
tap.test('should set spinner style', async () => {
testSpinner = new SmartlogSourceInteractive();
testSpinner.setSpeed(10); // Fast animation
testSpinner.setSpinnerStyle('line');
testSpinner.text('Custom style spinner');
// Visual effect can't be easily tested, but we can verify it doesn't throw errors
expect(testSpinner.isStarted()).toBeTrue();
cleanupSpinner(testSpinner);
});
tap.test('should set spinner color', async () => {
testSpinner = new SmartlogSourceInteractive();
testSpinner.setSpeed(10); // Fast animation
testSpinner.setColor('green');
testSpinner.text('Green spinner');
// Visual effect can't be easily tested, but we can verify it doesn't throw errors
expect(testSpinner.isStarted()).toBeTrue();
cleanupSpinner(testSpinner);
});
tap.test('should set animation speed', async () => {
testSpinner = new SmartlogSourceInteractive();
testSpinner.setSpeed(10); // Actually set fast for testing
testSpinner.text('Slow spinner');
// Visual effect can't be easily tested, but we can verify it doesn't throw errors
expect(testSpinner.isStarted()).toBeTrue();
cleanupSpinner(testSpinner);
});
// Test progress bar functionality
let testProgressBar: SmartlogProgressBar;
tap.test('should create a progress bar instance', async () => {
testProgressBar = new SmartlogProgressBar({
total: 100
});
expect(testProgressBar).toBeTruthy();
});
tap.test('should update progress bar value', async () => {
testProgressBar.update(50);
// Visual effect can't be easily tested, but we can verify it doesn't throw errors
});
tap.test('should increment progress bar', async () => {
const initialValue = 50;
const increment = 10;
testProgressBar = new SmartlogProgressBar({ total: 100 });
testProgressBar.update(initialValue);
testProgressBar.increment(increment);
// Visual effect can't be easily tested, but we can verify it doesn't throw errors
});
tap.test('should complete progress bar', async () => {
testProgressBar = new SmartlogProgressBar({ total: 100 });
testProgressBar.update(50);
testProgressBar.update(100); // Update to 100% to simulate completion
// Visual effect can't be easily tested, but we can verify it doesn't throw errors
});
tap.test('should set progress bar color', async () => {
testProgressBar = new SmartlogProgressBar({ total: 100 });
testProgressBar.setColor('blue');
testProgressBar.update(50);
// Visual effect can't be easily tested, but we can verify it doesn't throw errors
});
tap.test('should handle custom progress bar options', async () => {
testProgressBar = new SmartlogProgressBar({
total: 100,
width: 40,
complete: '=',
incomplete: '-',
showEta: false,
showPercent: true,
showCount: true
});
testProgressBar.update(30);
// Visual effect can't be easily tested, but we can verify it doesn't throw errors
});
// Test backward compatibility with SmartlogSourceOra
let testSourceOra: SmartlogSourceOra;
tap.test('should create a SmartlogSourceOra instance for backward compatibility', async () => {
testSourceOra = new SmartlogSourceOra();
expect(testSourceOra).toBeTruthy();
expect(testSourceOra.isStarted()).toBeFalse();
});
tap.test('should maintain compatibility with old API', async () => {
testSourceOra.setSpeed(10); // Fast animation
testSourceOra.text('Testing backward compatibility');
expect(testSourceOra.isStarted()).toBeTrue();
testSourceOra.finishSuccess('Success');
expect(testSourceOra.isStarted()).toBeFalse();
});
export default tap.start();

View File

@ -1,75 +0,0 @@
import { expect, tap } from '@push.rocks/tapbundle';
import { SmartlogSourceOra } from '../ts_source_ora/index.js';
let testSourceOra: SmartlogSourceOra;
tap.test('should create a SmartlogSourceOra instance', async () => {
testSourceOra = new SmartlogSourceOra();
expect(testSourceOra).toBeTruthy();
expect(testSourceOra.started).toBeFalse();
});
tap.test('should set text and start spinner', async () => {
const testText = 'Testing ora spinner';
testSourceOra.text(testText);
expect(testSourceOra.started).toBeTrue();
expect(testSourceOra.oraInstance.text).toEqual(testText);
});
tap.test('should update text', async () => {
const newText = 'Updated text';
testSourceOra.text(newText);
expect(testSourceOra.oraInstance.text).toEqual(newText);
expect(testSourceOra.started).toBeTrue();
});
tap.test('should stop spinner', async () => {
testSourceOra.stop();
// We can't easily test the visual state, but we can verify it doesn't throw errors
});
tap.test('should finish with success', async () => {
testSourceOra = new SmartlogSourceOra();
testSourceOra.text('Starting again');
const successText = 'Operation successful';
testSourceOra.finishSuccess(successText);
expect(testSourceOra.started).toBeFalse();
});
tap.test('should finish with failure', async () => {
testSourceOra = new SmartlogSourceOra();
testSourceOra.text('Starting again');
const failText = 'Operation failed';
testSourceOra.finishFail(failText);
expect(testSourceOra.started).toBeFalse();
});
tap.test('should handle success and next', async () => {
testSourceOra = new SmartlogSourceOra();
testSourceOra.text('Starting again');
const nextText = 'Next operation';
testSourceOra.successAndNext(nextText);
expect(testSourceOra.started).toBeTrue();
expect(testSourceOra.oraInstance.text).toEqual(nextText);
});
tap.test('should handle fail and next', async () => {
testSourceOra = new SmartlogSourceOra();
testSourceOra.text('Starting again');
const nextText = 'Next operation after failure';
testSourceOra.failAndNext(nextText);
expect(testSourceOra.started).toBeTrue();
expect(testSourceOra.oraInstance.text).toEqual(nextText);
});
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 * as smartlog from '../ts/index.js';
let testConsoleLog: smartlog.ConsoleLog;

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartlog',
version: '3.0.8',
version: '3.1.8',
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
private logToConsole(logPackageArg: ILogPackage) {
let logString: string;
try {
logString =
this.localBl[logPackageArg.level].prefix +
const style = this.localBl[logPackageArg.level] ?? this.localBl.info;
const logString =
style.prefix +
plugins.consolecolor.coloredString(
logPackageArg.message,
this.localBl[logPackageArg.level].textColor
style.textColor
);
console.log(logString);
return true;
} catch (error) {
// typo fix: use the defined error.prefix, not a non-existent errorPrefix
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;
}
@ -89,6 +92,10 @@ export class DestinationLocal implements ILogDestination {
prefix: plugins.consolecolor.coloredString(' silly ', 'white', 'blue') + ' ',
textColor: 'blue',
},
debug: {
prefix: plugins.consolecolor.coloredString(' debug ', 'pink', 'black') + ' ',
textColor: 'pink',
},
error: {
prefix:
plugins.consolecolor.coloredString(' ', 'red', 'red') +

View File

@ -0,0 +1,417 @@
import * as plugins from './smartlog-source-interactive.plugins.js';
/**
* Utility to detect if the environment is interactive
* Checks for TTY capability and common CI environment variables
*/
const isInteractive = () => {
try {
return Boolean(
// Check TTY capability
process.stdout && process.stdout.isTTY &&
// Additional checks for non-interactive environments
!('CI' in process.env) &&
!process.env.GITHUB_ACTIONS &&
!process.env.JENKINS_URL &&
!process.env.GITLAB_CI &&
!process.env.TRAVIS &&
!process.env.CIRCLECI &&
process.env.TERM !== 'dumb'
);
} catch (e) {
// If any error occurs (e.g., in browser environments without process),
// assume a non-interactive environment to be safe
return false;
}
};
// Helper to log messages in non-interactive mode
const logMessage = (message: string, prefix = '') => {
if (prefix) {
console.log(`${prefix} ${message}`);
} else {
console.log(message);
}
};
// Spinner frames and styles
const spinnerFrames = {
dots: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
line: ['|', '/', '-', '\\'],
star: ['✶', '✸', '✹', '✺', '✹', '✷'],
simple: ['-', '\\', '|', '/']
};
// Color names mapping to ANSI color codes
const colors = {
black: '\u001b[30m',
red: '\u001b[31m',
green: '\u001b[32m',
yellow: '\u001b[33m',
blue: '\u001b[34m',
magenta: '\u001b[35m',
cyan: '\u001b[36m',
white: '\u001b[37m',
gray: '\u001b[90m',
reset: '\u001b[0m'
};
/**
* A class for creating interactive spinners
* Automatically handles non-interactive environments
*/
export class SmartlogSourceInteractive {
private textContent: string = 'loading';
private currentFrame: number = 0;
private interval: NodeJS.Timeout | null = null;
private started: boolean = false;
private spinnerStyle: keyof typeof spinnerFrames = 'dots';
private color: keyof typeof colors = 'cyan';
private frames: string[];
private frameInterval: number = 80;
private interactive: boolean;
constructor() {
this.frames = spinnerFrames[this.spinnerStyle];
this.interactive = isInteractive();
}
/**
* Sets the text for the spinner and starts it if not already started
*/
public text(textArg: string) {
this.textContent = textArg;
if (!this.interactive) {
// In non-interactive mode, just log the message with a loading indicator
logMessage(textArg, '[Loading]');
this.started = true;
return;
}
if (!this.started) {
this.started = true;
this.start();
} else {
this.renderFrame();
}
}
/**
* Starts the spinner animation
*/
private start() {
if (!this.interactive) {
return; // No animation in non-interactive mode
}
if (this.interval) {
clearInterval(this.interval);
}
this.renderFrame();
this.interval = setInterval(() => {
this.currentFrame = (this.currentFrame + 1) % this.frames.length;
this.renderFrame();
}, this.frameInterval);
}
/**
* Renders the current frame of the spinner
*/
private renderFrame() {
if (!this.started || !this.interactive) return;
const frame = this.frames[this.currentFrame];
const colorCode = colors[this.color];
const resetCode = colors.reset;
// Only use ANSI escape codes in interactive mode
process.stdout.write('\r\x1b[2K'); // Clear the current line
process.stdout.write(`${colorCode}${frame}${resetCode} ${this.textContent}`);
}
/**
* Stops the spinner
*/
public stop() {
// Always clear the interval even in non-interactive mode
// This prevents memory leaks in tests and long-running applications
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
if (!this.interactive) {
return; // No need to clear the line in non-interactive mode
}
process.stdout.write('\r\x1b[2K'); // Clear the current line
}
/**
* Marks the spinner as successful and optionally displays a success message
*/
public finishSuccess(textArg?: string) {
const message = textArg || this.textContent;
// Always stop the spinner first to clean up intervals
this.stop();
if (!this.interactive) {
logMessage(message, '[Success]');
} else {
const successSymbol = colors.green + '✓' + colors.reset;
process.stdout.write(`${successSymbol} ${message}\n`);
}
this.started = false;
}
/**
* Marks the spinner as failed and optionally displays a failure message
*/
public finishFail(textArg?: string) {
const message = textArg || this.textContent;
// Always stop the spinner first to clean up intervals
this.stop();
if (!this.interactive) {
logMessage(message, '[Failed]');
} else {
const failSymbol = colors.red + '✗' + colors.reset;
process.stdout.write(`${failSymbol} ${message}\n`);
}
this.started = false;
}
/**
* Marks the current spinner as successful and starts a new one
*/
public successAndNext(textArg: string) {
this.finishSuccess();
this.text(textArg);
}
/**
* Marks the current spinner as failed and starts a new one
*/
public failAndNext(textArg: string) {
this.finishFail();
this.text(textArg);
}
/**
* Sets the spinner style
*/
public setSpinnerStyle(style: keyof typeof spinnerFrames) {
this.spinnerStyle = style;
this.frames = spinnerFrames[style];
return this;
}
/**
* Sets the spinner color
*/
public setColor(colorName: keyof typeof colors) {
if (colorName in colors) {
this.color = colorName;
}
return this;
}
/**
* Sets the animation speed in milliseconds
*/
public setSpeed(ms: number) {
this.frameInterval = ms;
if (this.started) {
this.stop();
this.start();
}
return this;
}
/**
* Gets the current started state
*/
public isStarted() {
return this.started;
}
}
export interface IProgressBarOptions {
total: number;
width?: number;
complete?: string;
incomplete?: string;
renderThrottle?: number;
clear?: boolean;
showEta?: boolean;
showPercent?: boolean;
showCount?: boolean;
}
export class SmartlogProgressBar {
private total: number;
private current: number = 0;
private width: number;
private completeChar: string;
private incomplete: string;
private renderThrottle: number;
private clear: boolean;
private showEta: boolean;
private showPercent: boolean;
private showCount: boolean;
private color: keyof typeof colors = 'green';
private startTime: number | null = null;
private lastRenderTime: number = 0;
private interactive: boolean;
private lastLoggedPercent: number = 0;
private logThreshold: number = 10; // Log every 10% in non-interactive mode
constructor(options: IProgressBarOptions) {
this.total = options.total;
this.width = options.width || 30;
this.completeChar = options.complete || '█';
this.incomplete = options.incomplete || '░';
this.renderThrottle = options.renderThrottle || 16;
this.clear = options.clear !== undefined ? options.clear : false;
this.showEta = options.showEta !== undefined ? options.showEta : true;
this.showPercent = options.showPercent !== undefined ? options.showPercent : true;
this.showCount = options.showCount !== undefined ? options.showCount : true;
this.interactive = isInteractive();
}
/**
* Update the progress bar to a specific value
*/
public update(value: number): this {
if (this.startTime === null) {
this.startTime = Date.now();
}
this.current = Math.min(value, this.total);
if (!this.interactive) {
// In non-interactive mode, log progress at certain thresholds
const percent = Math.floor((this.current / this.total) * 100);
const currentThreshold = Math.floor(percent / this.logThreshold) * this.logThreshold;
if (currentThreshold > this.lastLoggedPercent || percent === 100) {
this.lastLoggedPercent = currentThreshold;
logMessage(`Progress: ${percent}% (${this.current}/${this.total})`);
}
return this;
}
// Throttle rendering to avoid excessive updates in interactive mode
const now = Date.now();
if (now - this.lastRenderTime < this.renderThrottle) {
return this;
}
this.lastRenderTime = now;
this.render();
return this;
}
/**
* Increment the progress bar by a value
*/
public increment(value: number = 1): this {
return this.update(this.current + value);
}
/**
* Mark the progress bar as complete
*/
public complete(): this {
this.update(this.total);
if (!this.interactive) {
logMessage(`Completed: 100% (${this.total}/${this.total})`);
return this;
}
if (this.clear) {
process.stdout.write('\r\x1b[2K');
} else {
process.stdout.write('\n');
}
return this;
}
/**
* Set the color of the progress bar
*/
public setColor(colorName: keyof typeof colors): this {
if (colorName in colors) {
this.color = colorName;
}
return this;
}
/**
* Render the progress bar
*/
private render(): void {
if (!this.interactive) {
return; // Don't render in non-interactive mode
}
// Calculate percent complete
const percent = Math.floor((this.current / this.total) * 100);
const completeLength = Math.round((this.current / this.total) * this.width);
const incompleteLength = this.width - completeLength;
// Build the progress bar
const completePart = colors[this.color] + this.completeChar.repeat(completeLength) + colors.reset;
const incompletePart = this.incomplete.repeat(incompleteLength);
const progressBar = `[${completePart}${incompletePart}]`;
// Calculate ETA if needed
let etaStr = '';
if (this.showEta && this.startTime !== null && this.current > 0) {
const elapsed = (Date.now() - this.startTime) / 1000;
const rate = this.current / elapsed;
const remaining = Math.max(0, this.total - this.current);
const eta = Math.round(remaining / rate);
const mins = Math.floor(eta / 60);
const secs = eta % 60;
etaStr = ` eta: ${mins}m${secs}s`;
}
// Build additional information
const percentStr = this.showPercent ? ` ${percent}%` : '';
const countStr = this.showCount ? ` ${this.current}/${this.total}` : '';
// Clear the line and render
process.stdout.write('\r\x1b[2K');
process.stdout.write(`${progressBar}${percentStr}${countStr}${etaStr}`);
}
}
// For backward compatibility with 'source-ora' module
export class SmartlogSourceOra extends SmartlogSourceInteractive {
// Add a stub for the oraInstance property for backward compatibility
public get oraInstance() {
// Use public methods instead of accessing private properties
const instance = this;
return {
get text() { return ''; }, // We can't access private textContent directly
start: () => instance.text(''), // This starts the spinner
stop: () => instance.stop(),
succeed: (text?: string) => instance.finishSuccess(text),
fail: (text?: string) => instance.finishFail(text)
};
}
public set oraInstance(value: any) {
// No-op, just for compatibility
}
}

View File

@ -0,0 +1,10 @@
// pushrocks scope
import * as smartlogInterfaces from '../dist_ts_interfaces/index.js';
import * as consolecolor from '@push.rocks/consolecolor';
export { smartlogInterfaces, consolecolor };
// node.js internal
import { stdout, stderr } from 'process';
export { stdout, stderr };

View File

@ -1,40 +0,0 @@
import * as plugins from './smartlog-source-ora.plugins.js';
export class SmartlogSourceOra {
public oraInstance = plugins.ora('loading');
public started = false;
constructor() {}
public text(textArg: string) {
this.oraInstance.text = textArg;
if (!this.started) {
this.started = true;
this.oraInstance.start();
}
}
public stop() {
this.oraInstance.stop();
}
public finishSuccess(textArg?: string) {
this.oraInstance.succeed(textArg);
this.started = false;
}
public finishFail(textArg?: string) {
this.oraInstance.fail(textArg);
this.started = false;
}
public successAndNext(textArg: string) {
this.finishSuccess();
this.text(textArg);
}
public failAndNext(textArg: string) {
this.finishFail();
this.text(textArg);
}
}

View File

@ -1,9 +0,0 @@
// pushrocks scope
import * as smartlogInterfaces from '../dist_ts_interfaces/index.js';
export { smartlogInterfaces };
// third party scope
import ora from 'ora';
export { ora };