Compare commits
141 Commits
Author | SHA1 | Date | |
---|---|---|---|
e133da8076 | |||
d502ab8cc9 | |||
d1c05fb9ae | |||
f81971d148 | |||
aa6a27970a | |||
b31d9f0c36 | |||
e6cef68a26 | |||
aa327efeac | |||
7cbc64ed8d | |||
2c49ef49c2 | |||
823784e6b6 | |||
a98f48409d | |||
a2ae8c0c83 | |||
6ef2d961a6 | |||
f80ec7ddfe | |||
f2823c2645 | |||
75783b0e87 | |||
13e1582732 | |||
7e2f076b35 | |||
7e8a404fcf | |||
09da3a1e2d | |||
f542596eae | |||
1ca8cf89de | |||
9b63777a76 | |||
e853b2d5e4 | |||
a88b614e80 | |||
92a48c415d | |||
fe676b70a9 | |||
51bed6bd30 | |||
ac4f583580 | |||
ff1192f09a | |||
459d3cc0e5 | |||
fc2619b757 | |||
fe367372c3 | |||
694a8cf981 | |||
e849e4508b | |||
f8f48d67e0 | |||
ed2b74d436 | |||
0caf48a734 | |||
c4d6402fd9 | |||
83bc0c512b | |||
102e8faf92 | |||
87da0f1169 | |||
b53c49ca28 | |||
47bde8b4f8 | |||
d71de485d6 | |||
964666902f | |||
d5d6d7bf79 | |||
02d10dd08c | |||
4062157544 | |||
a673844fb3 | |||
53248a3a3d | |||
0043a553a7 | |||
13981404f3 | |||
db951d1877 | |||
26c84b3a04 | |||
b3d8cf68f1 | |||
60ae0fed4e | |||
a03e821c02 | |||
592178f066 | |||
260af690ff | |||
7bd12e7a01 | |||
f8a49e033d | |||
3066503a70 | |||
cf899609be | |||
7be0e70754 | |||
8b0ceb759d | |||
7b5cfb2c95 | |||
a4a5b18849 | |||
47583bd955 | |||
018bc7054a | |||
5ca4cb9964 | |||
27bb9a789c | |||
5f7e68d5b7 | |||
da0edc478c | |||
d2be068597 | |||
4113a9a211 | |||
3575262001 | |||
1cc75afc32 | |||
7d72b24770 | |||
ffff60772c | |||
a604b8e375 | |||
2cc3e6c906 | |||
5a475260dd | |||
9c79a26d04 | |||
3fbd87cab1 | |||
5fe5c1d315 | |||
1b4d9b33ef | |||
7598e9148b | |||
89429ac679 | |||
9f81cdfb8a | |||
ab9a7891a7 | |||
58358dd479 | |||
fc13271878 | |||
7cd739ff23 | |||
7ec6579cc3 | |||
0c6240ae60 | |||
5d9fb7c25a | |||
6ee63d1e96 | |||
e648a787e5 | |||
96bc87ecbd | |||
de81a174f8 | |||
027216914d | |||
34cc6cbed5 | |||
0bcca99349 | |||
dc72beaf61 | |||
3b706a3b54 | |||
acde7f2204 | |||
890d592072 | |||
31d8aa84ec | |||
3050a63323 | |||
9e294ee357 | |||
ba19654a5e | |||
0ac464875a | |||
fa074facbb | |||
ac4d466ab4 | |||
a0aa3c1122 | |||
5dff4961fb | |||
3a98c2e7d9 | |||
39d08ef53a | |||
74e6bc7a3c | |||
5d0056558a | |||
2b920e2f5e | |||
793cd38381 | |||
7a05e4484d | |||
2fe657f5af | |||
5508beae25 | |||
f2c0f1acff | |||
5805cc51a6 | |||
c9c38368c1 | |||
640eddae2d | |||
ade4d86597 | |||
d4cc9dbcd0 | |||
cde3686209 | |||
485e04c0b3 | |||
0ee2b8295a | |||
4fd4de20c2 | |||
accf03f1b4 | |||
8e8e2c7bd6 | |||
698d5927cc | |||
3d8e2f881b |
66
.gitea/workflows/default_nottags.yaml
Normal file
66
.gitea/workflows/default_nottags.yaml
Normal file
@@ -0,0 +1,66 @@
|
||||
name: Default (not tags)
|
||||
|
||||
on:
|
||||
push:
|
||||
tags-ignore:
|
||||
- '**'
|
||||
|
||||
env:
|
||||
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
|
||||
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
|
||||
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
|
||||
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
|
||||
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
|
||||
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
|
||||
|
||||
jobs:
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
continue-on-error: true
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Install pnpm and npmci
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @ship.zone/npmci
|
||||
|
||||
- name: Run npm prepare
|
||||
run: npmci npm prepare
|
||||
|
||||
- name: Audit production dependencies
|
||||
run: |
|
||||
npmci command npm config set registry https://registry.npmjs.org
|
||||
npmci command pnpm audit --audit-level=high --prod
|
||||
continue-on-error: true
|
||||
|
||||
- name: Audit development dependencies
|
||||
run: |
|
||||
npmci command npm config set registry https://registry.npmjs.org
|
||||
npmci command pnpm audit --audit-level=high --dev
|
||||
continue-on-error: true
|
||||
|
||||
test:
|
||||
if: ${{ always() }}
|
||||
needs: security
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Test stable
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
npmci npm test
|
||||
|
||||
- name: Test build
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
npmci npm build
|
124
.gitea/workflows/default_tags.yaml
Normal file
124
.gitea/workflows/default_tags.yaml
Normal file
@@ -0,0 +1,124 @@
|
||||
name: Default (tags)
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
env:
|
||||
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
|
||||
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
|
||||
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
|
||||
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
|
||||
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
|
||||
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
|
||||
|
||||
jobs:
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
continue-on-error: true
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Audit production dependencies
|
||||
run: |
|
||||
npmci command npm config set registry https://registry.npmjs.org
|
||||
npmci command pnpm audit --audit-level=high --prod
|
||||
continue-on-error: true
|
||||
|
||||
- name: Audit development dependencies
|
||||
run: |
|
||||
npmci command npm config set registry https://registry.npmjs.org
|
||||
npmci command pnpm audit --audit-level=high --dev
|
||||
continue-on-error: true
|
||||
|
||||
test:
|
||||
if: ${{ always() }}
|
||||
needs: security
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Test stable
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
npmci npm test
|
||||
|
||||
- name: Test build
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
npmci npm build
|
||||
|
||||
release:
|
||||
needs: test
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Release
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm publish
|
||||
|
||||
metadata:
|
||||
needs: test
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ${{ env.IMAGE }}
|
||||
continue-on-error: true
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Prepare
|
||||
run: |
|
||||
pnpm install -g pnpm
|
||||
pnpm install -g @ship.zone/npmci
|
||||
npmci npm prepare
|
||||
|
||||
- name: Code quality
|
||||
run: |
|
||||
npmci command npm install -g typescript
|
||||
npmci npm install
|
||||
|
||||
- name: Trigger
|
||||
run: npmci trigger
|
||||
|
||||
- name: Build docs and upload artifacts
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
pnpm install -g @git.zone/tsdoc
|
||||
npmci command tsdoc
|
||||
continue-on-error: true
|
19
.gitignore
vendored
19
.gitignore
vendored
@@ -1,5 +1,20 @@
|
||||
.nogit/
|
||||
node_modules/
|
||||
|
||||
# artifacts
|
||||
coverage/
|
||||
public/
|
||||
pages/
|
||||
|
||||
# installs
|
||||
node_modules/
|
||||
|
||||
# caches
|
||||
.yarn/
|
||||
.cache/
|
||||
.rpt2_cache
|
||||
|
||||
# builds
|
||||
dist/
|
||||
dist_*/
|
||||
|
||||
#------# custom
|
||||
**/.claude/settings.local.json
|
||||
|
130
.gitlab-ci.yml
130
.gitlab-ci.yml
@@ -1,130 +0,0 @@
|
||||
# gitzone standard
|
||||
image: hosttoday/ht-docker-node:npmci
|
||||
|
||||
cache:
|
||||
paths:
|
||||
- .npmci_cache/
|
||||
key: "$CI_BUILD_STAGE"
|
||||
|
||||
stages:
|
||||
- security
|
||||
- test
|
||||
- release
|
||||
- metadata
|
||||
|
||||
# ====================
|
||||
# security stage
|
||||
# ====================
|
||||
mirror:
|
||||
stage: security
|
||||
script:
|
||||
- npmci git mirror
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
snyk:
|
||||
stage: security
|
||||
script:
|
||||
- npmci command npm install -g snyk
|
||||
- npmci command npm install --ignore-scripts
|
||||
- npmci command snyk test
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
# ====================
|
||||
# test stage
|
||||
# ====================
|
||||
testLEGACY:
|
||||
stage: test
|
||||
script:
|
||||
- npmci node install legacy
|
||||
- npmci npm install
|
||||
- npmci npm test
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
allow_failure: true
|
||||
|
||||
testLTS:
|
||||
stage: test
|
||||
script:
|
||||
- npmci node install lts
|
||||
- npmci npm install
|
||||
- npmci npm test
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
testSTABLE:
|
||||
stage: test
|
||||
script:
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci npm test
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
release:
|
||||
stage: release
|
||||
script:
|
||||
- npmci node install stable
|
||||
- npmci npm publish
|
||||
only:
|
||||
- tags
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
# ====================
|
||||
# metadata stage
|
||||
# ====================
|
||||
codequality:
|
||||
stage: metadata
|
||||
image: docker:stable
|
||||
allow_failure: true
|
||||
services:
|
||||
- docker:stable-dind
|
||||
script:
|
||||
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
|
||||
- docker run
|
||||
--env SOURCE_CODE="$PWD"
|
||||
--volume "$PWD":/code
|
||||
--volume /var/run/docker.sock:/var/run/docker.sock
|
||||
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
|
||||
artifacts:
|
||||
paths: [codeclimate.json]
|
||||
tags:
|
||||
- docker
|
||||
- priv
|
||||
|
||||
trigger:
|
||||
stage: metadata
|
||||
script:
|
||||
- npmci trigger
|
||||
only:
|
||||
- tags
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
pages:
|
||||
image: hosttoday/ht-docker-node:npmci
|
||||
stage: metadata
|
||||
script:
|
||||
- npmci command npm install -g npmpage
|
||||
- npmci command npmpage
|
||||
tags:
|
||||
- docker
|
||||
- notpriv
|
||||
only:
|
||||
- tags
|
||||
artifacts:
|
||||
expire_in: 1 week
|
||||
paths:
|
||||
- public
|
11
.vscode/launch.json
vendored
Normal file
11
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"command": "npm test",
|
||||
"name": "Run npm test",
|
||||
"request": "launch",
|
||||
"type": "node-terminal"
|
||||
}
|
||||
]
|
||||
}
|
26
.vscode/settings.json
vendored
Normal file
26
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"json.schemas": [
|
||||
{
|
||||
"fileMatch": ["/npmextra.json"],
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"npmci": {
|
||||
"type": "object",
|
||||
"description": "settings for npmci"
|
||||
},
|
||||
"gitzone": {
|
||||
"type": "object",
|
||||
"description": "settings for gitzone",
|
||||
"properties": {
|
||||
"projectType": {
|
||||
"type": "string",
|
||||
"enum": ["website", "element", "service", "npm", "wcc"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
300
API.md
Normal file
300
API.md
Normal 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
|
387
changelog.md
Normal file
387
changelog.md
Normal file
@@ -0,0 +1,387 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-09-01 - 3.1.9 - fix(docs)
|
||||
Update README: expand documentation, examples and usage guides
|
||||
|
||||
- Fully rewrote README to a comprehensive documentation page with badges, motivation and feature overview.
|
||||
- Added Quick Start, detailed usage examples and code snippets for Smartlog, destinations, and custom destinations.
|
||||
- Documented interactive console features (spinners, progress bars) including non-interactive fallbacks and configuration options.
|
||||
- Expanded sections on built-in destinations (console, file, devtools, ClickHouse, receiver) with practical examples and env-driven configuration.
|
||||
- Added integration examples (PM2, Docker), CLI usage, advanced features (context management, scoped logging, minimum log levels) and best practices.
|
||||
- Included API reference pointers and contributing / license information.
|
||||
|
||||
## 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
|
||||
|
||||
- Add separate Gitea workflows for tag and non-tag pushes to automate testing, auditing, and release steps
|
||||
- Revise package.json exports and update dependency versions and build scripts for improved module resolution
|
||||
- Enhance tsconfig settings with baseUrl and paths for consistency
|
||||
- Refine source code formatting and adjust test cases for better maintenance
|
||||
|
||||
## 2024-06-06 - 3.0.7 - no notable changes
|
||||
This release contains no detailed changes.
|
||||
|
||||
## 2024-06-06 - 3.0.6 - core
|
||||
A few fixes and updates were made in this release.
|
||||
|
||||
- fix(core): update
|
||||
- update description
|
||||
|
||||
## 2024-05-17 - 3.0.5 - core
|
||||
A minor core fix was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2024-05-17 - 3.0.4 - core
|
||||
This release includes several updates to core files and configuration.
|
||||
|
||||
- fix(core): update
|
||||
- update tsconfig
|
||||
- update npmextra.json: githost
|
||||
- update npmextra.json: githost
|
||||
- update npmextra.json: githost
|
||||
|
||||
## 2023-08-08 - 3.0.3 - core
|
||||
A simple core update was performed.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2023-07-12 - 3.0.2 - core
|
||||
Core updates and a change of organizational scheme were introduced.
|
||||
|
||||
- fix(core): update
|
||||
- switch to new org scheme (x2)
|
||||
|
||||
## 2022-10-26 - 3.0.1 - core
|
||||
A core fix was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2022-07-26 - 3.0.0 - core
|
||||
A minor core update was made.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2022-06-26 - 2.0.44 - core
|
||||
A breaking change switched the module system to esm.
|
||||
|
||||
- BREAKING CHANGE(core): switch to esm
|
||||
|
||||
## 2021-07-21 - 2.0.43 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2021-07-20 - 2.0.42 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2021-07-20 - 2.0.41 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2021-07-20 - 2.0.40 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2021-07-06 - 2.0.39 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-09-08 - 2.0.38 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-09-07 - 2.0.37 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-09-07 - 2.0.36 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-08-02 - 2.0.35 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-11 - 2.0.34 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-11 - 2.0.33 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-11 - 2.0.32 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-11 - 2.0.31 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-11 - 2.0.30 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-11 - 2.0.29 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-11 - 2.0.28 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-08 - 2.0.27 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-08 - 2.0.26 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-08 - 2.0.25 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-08 - 2.0.24 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-07 - 2.0.23 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-05 - 2.0.22 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2020-06-05 - 2.0.21 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2019-10-22 - 2.0.20 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2019-10-22 - 2.0.19 - core
|
||||
Dependencies were updated in the core.
|
||||
|
||||
- fix(core): update dependencies
|
||||
|
||||
## 2019-01-30 - 2.0.18 - license
|
||||
License files were updated.
|
||||
|
||||
- fix(license): update license files
|
||||
|
||||
## 2019-01-30 - 2.0.17 - readme
|
||||
A typo in the readme was fixed.
|
||||
|
||||
- fix(readme): fix typo
|
||||
|
||||
## 2019-01-30 - 2.0.16 - readme
|
||||
A typo in the readme was fixed.
|
||||
|
||||
- fix(readme): fix typo
|
||||
|
||||
## 2019-01-28 - 2.0.15 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2019-01-28 - 2.0.14 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2019-01-22 - 2.0.13 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2019-01-22 - 2.0.12 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2019-01-18 - 2.0.11 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2019-01-15 - 2.0.10 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2019-01-15 - 2.0.9 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2018-11-11 - 2.0.8 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2018-11-04 - 2.0.7 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2018-11-04 - 2.0.6 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2018-11-04 - 2.0.5 - api
|
||||
An API improvement was made.
|
||||
|
||||
- fix(api): streamline api
|
||||
|
||||
## 2018-11-04 - 2.0.4 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2018-11-03 - 2.0.3 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2018-10-31 - 2.0.2 - core
|
||||
A core update was applied.
|
||||
|
||||
- fix(core): update
|
||||
|
||||
## 2018-10-30 - 2.0.1 - core
|
||||
A new log router was implemented in core.
|
||||
|
||||
- fix(core): implement log router
|
||||
|
||||
## 2018-07-10 - 2.0.0 - core
|
||||
Console enabling was fixed.
|
||||
|
||||
- fix(.enableConsole()): now works
|
||||
|
||||
## 2018-07-10 - 1.0.6 - core
|
||||
A breaking change added a simple defaultLogger to core.
|
||||
|
||||
- BREAKING CHANGE(core): now has simple defaultLogger
|
||||
|
||||
## 2018-07-08 - 1.0.5 - npm
|
||||
Package distribution was fixed.
|
||||
|
||||
- fix(npm): package distribution
|
||||
|
||||
## 2018-06-05 - 1.0.4 - package
|
||||
The package name was updated.
|
||||
|
||||
- fix(package): update package name
|
||||
|
||||
## 2018-06-05 - 1.0.3 - core
|
||||
Several changes were made to update standards and system behavior.
|
||||
|
||||
- fix(core): update to latest standards
|
||||
- system change
|
||||
|
||||
## 2018-01-28 - 1.0.2 - docs
|
||||
Documentation was added to the readme.
|
||||
|
||||
- docs(readme): add readme
|
||||
|
||||
## 2018-01-28 - 1.0.1 - misc
|
||||
Initial cleanup and TypeScript support were introduced.
|
||||
|
||||
- fix(cleanup):
|
||||
- feat(ts): initial
|
||||
|
||||
## 2016-10-15 - 1.0.0 - no notable changes
|
||||
This initial release contains no detailed changes.
|
19
license
Normal file
19
license
Normal file
@@ -0,0 +1,19 @@
|
||||
Copyright (c) 2018 Lossless GmbH (hello@lossless.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@@ -1,8 +1,37 @@
|
||||
{
|
||||
"gitzone": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "code.foss.global",
|
||||
"gitscope": "push.rocks",
|
||||
"gitrepo": "smartlog",
|
||||
"description": "A minimalistic, distributed, and extensible logging tool supporting centralized log management.",
|
||||
"npmPackagename": "@push.rocks/smartlog",
|
||||
"license": "MIT",
|
||||
"projectDomain": "push.rocks",
|
||||
"keywords": [
|
||||
"logging",
|
||||
"log management",
|
||||
"typescript",
|
||||
"centralized logging",
|
||||
"json logging",
|
||||
"node.js",
|
||||
"distributed systems",
|
||||
"extensible logging",
|
||||
"log routing",
|
||||
"console logging",
|
||||
"log destinations",
|
||||
"log levels",
|
||||
"error tracking",
|
||||
"development tools"
|
||||
]
|
||||
}
|
||||
},
|
||||
"npmci": {
|
||||
"npmGlobalTools": [
|
||||
"npmts"
|
||||
],
|
||||
"npmGlobalTools": [],
|
||||
"npmAccessLevel": "public"
|
||||
},
|
||||
"tsdoc": {
|
||||
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
|
||||
}
|
||||
}
|
||||
}
|
422
package-lock.json
generated
422
package-lock.json
generated
@@ -1,422 +0,0 @@
|
||||
{
|
||||
"name": "smartlog",
|
||||
"version": "1.0.4",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
"@gitzone/tsrun": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@gitzone/tsrun/-/tsrun-1.0.4.tgz",
|
||||
"integrity": "sha512-frgbFyT+AhY3WtWp+n+lJesDjyBHKUrMi01s+tLEs9IkJNcTWGMCNiSV98Z5Zi392x84dk5ooTC9J+2YyqhNcw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ts-node": "^6.1.0",
|
||||
"typescript": "^2.9.1"
|
||||
}
|
||||
},
|
||||
"@types/code": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/code/-/code-4.0.4.tgz",
|
||||
"integrity": "sha512-w05ilMzX2+CZ6sxHCREp8YdczWLky2oj6asEq5uGpmQ/uI17ohPK8ui3ScJcOv2R9EmQ2aE0ZDgCyX6d+TojRw==",
|
||||
"dev": true
|
||||
},
|
||||
"@types/node": {
|
||||
"version": "8.10.18",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-8.10.18.tgz",
|
||||
"integrity": "sha512-WoepSz+wJlU5Bjq5oK6cO1oXe2FgPcjMtQPgKPS8fVaTAD0lxkScMCCbMimdkVCsykqaA4lvHWz3cmj28yimhA==",
|
||||
"dev": true
|
||||
},
|
||||
"ansi-256-colors": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-256-colors/-/ansi-256-colors-1.1.0.tgz",
|
||||
"integrity": "sha1-kQ3lDvzHwJ49gvL4er1rcAwYgYo=",
|
||||
"dev": true
|
||||
},
|
||||
"arrify": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz",
|
||||
"integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=",
|
||||
"dev": true
|
||||
},
|
||||
"beautycolor": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/beautycolor/-/beautycolor-1.0.11.tgz",
|
||||
"integrity": "sha512-Uxl/39+2uqixPzsrV+0NOHf0sJlWmsKnRTV0oz8+bfwnHPA/E+SZuh3Upn3OXobv0W7LZg5BVoLj1nkMj7m5jA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ansi-256-colors": "^1.1.0",
|
||||
"typings-global": "^1.0.14"
|
||||
}
|
||||
},
|
||||
"bindings": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.3.0.tgz",
|
||||
"integrity": "sha512-DpLh5EzMR2kzvX1KIlVC0VkC3iZtHKTgdtZ0a3pglBZdaQFjt5S9g9xd1lE+YvXyfd6mtCeRnrUfOLYiTMlNSw==",
|
||||
"dev": true
|
||||
},
|
||||
"buffer-from": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.0.tgz",
|
||||
"integrity": "sha512-c5mRlguI/Pe2dSZmpER62rSCu0ryKmWddzRYsuXc50U2/g8jMOulc31VZMa4mYx31U5xsmSOpDCgH88Vl9cDGQ==",
|
||||
"dev": true
|
||||
},
|
||||
"code": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/code/-/code-5.2.0.tgz",
|
||||
"integrity": "sha512-Ul69Vhv+L/sewD9azem9xvj6W+dW7XJ6UYust04KDEYQwyCb9M3ZkUjS7udFNSdvnYvbokBYDoXQXUg0P4DN5g==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"hoek": "5.x.x"
|
||||
}
|
||||
},
|
||||
"conventional-commit-types": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/conventional-commit-types/-/conventional-commit-types-2.2.0.tgz",
|
||||
"integrity": "sha1-XblXOdbCEqy+e29lahG5QLqmiUY=",
|
||||
"dev": true
|
||||
},
|
||||
"cz-conventional-changelog": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/cz-conventional-changelog/-/cz-conventional-changelog-2.1.0.tgz",
|
||||
"integrity": "sha1-L0vHOQ4yROTfKT5ro1Hkx0Cnx2Q=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"conventional-commit-types": "^2.0.0",
|
||||
"lodash.map": "^4.5.1",
|
||||
"longest": "^1.0.1",
|
||||
"right-pad": "^1.0.1",
|
||||
"word-wrap": "^1.0.3"
|
||||
}
|
||||
},
|
||||
"define-properties": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.2.tgz",
|
||||
"integrity": "sha1-g6c/L+pWmJj7c3GTyPhzyvbUXJQ=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"foreach": "^2.0.5",
|
||||
"object-keys": "^1.0.8"
|
||||
}
|
||||
},
|
||||
"diff": {
|
||||
"version": "3.5.0",
|
||||
"resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz",
|
||||
"integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==",
|
||||
"dev": true
|
||||
},
|
||||
"early": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/early/-/early-2.1.1.tgz",
|
||||
"integrity": "sha1-hB4jJU6l3FTYr67ugvWrZcAO4jw=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"beautycolor": "^1.0.7",
|
||||
"smartq": "^1.1.1",
|
||||
"typings-global": "^1.0.16"
|
||||
}
|
||||
},
|
||||
"es-abstract": {
|
||||
"version": "1.12.0",
|
||||
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.12.0.tgz",
|
||||
"integrity": "sha512-C8Fx/0jFmV5IPoMOFPA9P9G5NtqW+4cOPit3MIuvR2t7Ag2K15EJTpxnHAYTzL+aYQJIESYeXZmDBfOBE1HcpA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"es-to-primitive": "^1.1.1",
|
||||
"function-bind": "^1.1.1",
|
||||
"has": "^1.0.1",
|
||||
"is-callable": "^1.1.3",
|
||||
"is-regex": "^1.0.4"
|
||||
}
|
||||
},
|
||||
"es-to-primitive": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.1.1.tgz",
|
||||
"integrity": "sha1-RTVSSKiJeQNLZ5Lhm7gfK3l13Q0=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"is-callable": "^1.1.1",
|
||||
"is-date-object": "^1.0.1",
|
||||
"is-symbol": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"es6-error": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",
|
||||
"integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==",
|
||||
"dev": true
|
||||
},
|
||||
"foreach": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz",
|
||||
"integrity": "sha1-C+4AUBiusmDQo6865ljdATbsG5k=",
|
||||
"dev": true
|
||||
},
|
||||
"function-bind": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
|
||||
"integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==",
|
||||
"dev": true
|
||||
},
|
||||
"has": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
|
||||
"integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"function-bind": "^1.1.1"
|
||||
}
|
||||
},
|
||||
"hoek": {
|
||||
"version": "5.0.3",
|
||||
"resolved": "https://registry.npmjs.org/hoek/-/hoek-5.0.3.tgz",
|
||||
"integrity": "sha512-Bmr56pxML1c9kU+NS51SMFkiVQAb+9uFfXwyqR2tn4w2FPvmPt65eZ9aCcEfRXd9G74HkZnILC6p967pED4aiw==",
|
||||
"dev": true
|
||||
},
|
||||
"is-callable": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.3.tgz",
|
||||
"integrity": "sha1-hut1OSgF3cM69xySoO7fdO52BLI=",
|
||||
"dev": true
|
||||
},
|
||||
"is-date-object": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz",
|
||||
"integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=",
|
||||
"dev": true
|
||||
},
|
||||
"is-regex": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz",
|
||||
"integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"has": "^1.0.1"
|
||||
}
|
||||
},
|
||||
"is-symbol": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.1.tgz",
|
||||
"integrity": "sha1-PMWfAAJRlLarLjjbrmaJJWtmBXI=",
|
||||
"dev": true
|
||||
},
|
||||
"leakage": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/leakage/-/leakage-0.3.0.tgz",
|
||||
"integrity": "sha1-FdaYq9x2u8ZDlgH08wIOd+LVDDk=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"es6-error": "^4.0.2",
|
||||
"left-pad": "^1.1.3",
|
||||
"memwatch-next": "^0.3.0",
|
||||
"minimist": "^1.2.0",
|
||||
"pretty-bytes": "^4.0.2"
|
||||
}
|
||||
},
|
||||
"left-pad": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz",
|
||||
"integrity": "sha512-XI5MPzVNApjAyhQzphX8BkmKsKUxD4LdyK24iZeQGinBN9yTQT3bFlCBy/aVx2HrNcqQGsdot8ghrjyrvMCoEA==",
|
||||
"dev": true
|
||||
},
|
||||
"lodash.map": {
|
||||
"version": "4.6.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.map/-/lodash.map-4.6.0.tgz",
|
||||
"integrity": "sha1-dx7Hg540c9nEzeKLGTlMNWL09tM=",
|
||||
"dev": true
|
||||
},
|
||||
"longest": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz",
|
||||
"integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=",
|
||||
"dev": true
|
||||
},
|
||||
"make-error": {
|
||||
"version": "1.3.4",
|
||||
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.4.tgz",
|
||||
"integrity": "sha512-0Dab5btKVPhibSalc9QGXb559ED7G7iLjFXBaj9Wq8O3vorueR5K5jaE3hkG6ZQINyhA/JgG6Qk4qdFQjsYV6g==",
|
||||
"dev": true
|
||||
},
|
||||
"memwatch-next": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/memwatch-next/-/memwatch-next-0.3.0.tgz",
|
||||
"integrity": "sha1-IREFD5qQbgqi1ypOwPAInHhyb48=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"bindings": "^1.2.1",
|
||||
"nan": "^2.3.2"
|
||||
}
|
||||
},
|
||||
"minimist": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
|
||||
"integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=",
|
||||
"dev": true
|
||||
},
|
||||
"mkdirp": {
|
||||
"version": "0.5.1",
|
||||
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
|
||||
"integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"minimist": "0.0.8"
|
||||
},
|
||||
"dependencies": {
|
||||
"minimist": {
|
||||
"version": "0.0.8",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
|
||||
"integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=",
|
||||
"dev": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"nan": {
|
||||
"version": "2.10.0",
|
||||
"resolved": "https://registry.npmjs.org/nan/-/nan-2.10.0.tgz",
|
||||
"integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA==",
|
||||
"dev": true
|
||||
},
|
||||
"object-keys": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.0.11.tgz",
|
||||
"integrity": "sha1-xUYBd4rVYPEULODgG8yotW0TQm0=",
|
||||
"dev": true
|
||||
},
|
||||
"object.getownpropertydescriptors": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz",
|
||||
"integrity": "sha1-h1jIRvW0B62rDyNuCYbxSwUcqhY=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"define-properties": "^1.1.2",
|
||||
"es-abstract": "^1.5.1"
|
||||
}
|
||||
},
|
||||
"pretty-bytes": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-4.0.2.tgz",
|
||||
"integrity": "sha1-sr+C5zUNZcbDOqlaqlpPYyf2HNk=",
|
||||
"dev": true
|
||||
},
|
||||
"right-pad": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/right-pad/-/right-pad-1.0.1.tgz",
|
||||
"integrity": "sha1-jKCMLLtbVedNr6lr9/0aJ9VoyNA=",
|
||||
"dev": true
|
||||
},
|
||||
"smartchai": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/smartchai/-/smartchai-1.0.8.tgz",
|
||||
"integrity": "sha512-4N7WB8Al4bCMa0GE5UZGdJa/FkD1nmeOhcQYhowJUvpuYJdiicrcRNcNNy5gTnr0qGujWO+gs4N9z4lO7GDibA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@types/code": "^4.0.3",
|
||||
"code": "^5.1.0",
|
||||
"typings-global": "^1.0.20"
|
||||
}
|
||||
},
|
||||
"smartdelay": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/smartdelay/-/smartdelay-1.0.4.tgz",
|
||||
"integrity": "sha512-ab+d8ADiMMPKwrQNhoJYjmOR20VIIIxjknoEF9/PfMryic7tmvTmFrDMdcnMRohGNw/pN+4/I5dSUBdsDya7uw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"smartq": "^1.1.1",
|
||||
"typings-global": "^1.0.16"
|
||||
}
|
||||
},
|
||||
"smartlog-interfaces": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/smartlog-interfaces/-/smartlog-interfaces-1.0.8.tgz",
|
||||
"integrity": "sha512-2z1dj3/Jc7hQWprTj2TamUoSmchfeQ4cSLN7GbqenAwiTgRZiDxMNpYLkSFoUQM1w6T58hG0jfiG3IEXhmqctg=="
|
||||
},
|
||||
"smartq": {
|
||||
"version": "1.1.8",
|
||||
"resolved": "https://registry.npmjs.org/smartq/-/smartq-1.1.8.tgz",
|
||||
"integrity": "sha512-FURlYW/C3bLeZjJcBVyw7bxCyQoCXiXbLCZcDUKznhXHaLu35c8m33/a2H8CA0rtb82lvzN8dRLnBZAcNMzNHQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"util.promisify": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"source-map": {
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
|
||||
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
|
||||
"dev": true
|
||||
},
|
||||
"source-map-support": {
|
||||
"version": "0.5.6",
|
||||
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.6.tgz",
|
||||
"integrity": "sha512-N4KXEz7jcKqPf2b2vZF11lQIz9W5ZMuUcIOGj243lduidkf2fjkVKJS9vNxVWn3u/uxX38AcE8U9nnH9FPcq+g==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"buffer-from": "^1.0.0",
|
||||
"source-map": "^0.6.0"
|
||||
}
|
||||
},
|
||||
"tapbundle": {
|
||||
"version": "1.1.8",
|
||||
"resolved": "https://registry.npmjs.org/tapbundle/-/tapbundle-1.1.8.tgz",
|
||||
"integrity": "sha512-CjH1RrfVMzE0hZLtqpLQ6J9DO1+cYGbakImhZOPTRyrCJaf3P4+mCKJOUpCify2QW/70Y0Zg6uHIEh5yGxZvfA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@types/node": "^8.0.33",
|
||||
"early": "^2.1.1",
|
||||
"leakage": "^0.3.0",
|
||||
"smartchai": "^1.0.3",
|
||||
"smartdelay": "^1.0.3",
|
||||
"smartq": "^1.1.1",
|
||||
"typings-global": "^1.0.19"
|
||||
}
|
||||
},
|
||||
"ts-node": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-6.1.0.tgz",
|
||||
"integrity": "sha512-mw11Bq08RZgrU/bzcVw/Ti9wNyefpOanXgWsHg008wyVHjvFhWxNatVVrciOAu8BcWSECoNOSunRzUokKH8Mmw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"arrify": "^1.0.0",
|
||||
"diff": "^3.1.0",
|
||||
"make-error": "^1.1.1",
|
||||
"minimist": "^1.2.0",
|
||||
"mkdirp": "^0.5.1",
|
||||
"source-map-support": "^0.5.6",
|
||||
"yn": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"typescript": {
|
||||
"version": "2.9.1",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-2.9.1.tgz",
|
||||
"integrity": "sha512-h6pM2f/GDchCFlldnriOhs1QHuwbnmj6/v7499eMHqPeW4V2G0elua2eIc2nu8v2NdHV0Gm+tzX83Hr6nUFjQA==",
|
||||
"dev": true
|
||||
},
|
||||
"typings-global": {
|
||||
"version": "1.0.28",
|
||||
"resolved": "https://registry.npmjs.org/typings-global/-/typings-global-1.0.28.tgz",
|
||||
"integrity": "sha512-6VOwJWEY2971HOMHu/7sURzUXiD4/LiMJPsMAOqkHHAtS3MVpLFE5gzTiHilsH9KY5VE1mBQirWIgWFsDuo90A==",
|
||||
"dev": true
|
||||
},
|
||||
"util.promisify": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/util.promisify/-/util.promisify-1.0.0.tgz",
|
||||
"integrity": "sha512-i+6qA2MPhvoKLuxnJNpXAGhg7HphQOSUq2LKMZD0m15EiskXUkMvKdF4Uui0WYeCUGea+o2cw/ZuwehtfsrNkA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"define-properties": "^1.1.2",
|
||||
"object.getownpropertydescriptors": "^2.0.3"
|
||||
}
|
||||
},
|
||||
"word-wrap": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz",
|
||||
"integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==",
|
||||
"dev": true
|
||||
},
|
||||
"yn": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/yn/-/yn-2.0.0.tgz",
|
||||
"integrity": "sha1-5a2ryKz0CPY4X8dklWhMiOavaJo=",
|
||||
"dev": true
|
||||
}
|
||||
}
|
||||
}
|
94
package.json
94
package.json
@@ -1,23 +1,91 @@
|
||||
{
|
||||
"name": "smartlog",
|
||||
"version": "1.0.4",
|
||||
"name": "@push.rocks/smartlog",
|
||||
"version": "3.1.9",
|
||||
"private": false,
|
||||
"description": "winston based logger for large scale projects",
|
||||
"main": "dist/index.js",
|
||||
"typings": "dist/index.d.ts",
|
||||
"description": "A minimalistic, distributed, and extensible logging tool supporting centralized log management.",
|
||||
"keywords": [
|
||||
"logging",
|
||||
"log management",
|
||||
"typescript",
|
||||
"centralized logging",
|
||||
"json logging",
|
||||
"node.js",
|
||||
"distributed systems",
|
||||
"extensible logging",
|
||||
"log routing",
|
||||
"console logging",
|
||||
"log destinations",
|
||||
"log levels",
|
||||
"error tracking",
|
||||
"development tools"
|
||||
],
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist_ts/index.js"
|
||||
},
|
||||
"./context": "./dist_ts_context/index.js",
|
||||
"./interfaces": "./dist_ts_interfaces/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",
|
||||
"./destination-local": "./dist_ts_destination_local/index.js",
|
||||
"./destination-receiver": "./dist_ts_destination_receiver/index.js",
|
||||
"./receiver": "./dist_ts_receiver/index.js"
|
||||
},
|
||||
"author": "Lossless GmbH",
|
||||
"license": "UNLICENSED",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "(tsrun test/test.ts)",
|
||||
"build": "echo \"Not needed for now\"",
|
||||
"format": "(gitzone format)"
|
||||
"test": "(tstest test/**/*.ts --verbose)",
|
||||
"build": "(tsbuild tsfolders --allowimplicitany && tsbundle npm)",
|
||||
"format": "(gitzone format)",
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@gitzone/tsrun": "^1.0.4",
|
||||
"cz-conventional-changelog": "^2.1.0",
|
||||
"tapbundle": "^1.0.13"
|
||||
"@git.zone/tsbuild": "^2.5.1",
|
||||
"@git.zone/tsbundle": "^2.2.5",
|
||||
"@git.zone/tsrun": "^1.3.3",
|
||||
"@git.zone/tstest": "^1.9.0",
|
||||
"@types/node": "^22.15.20"
|
||||
},
|
||||
"dependencies": {
|
||||
"smartlog-interfaces": "^1.0.4"
|
||||
"@api.global/typedrequest-interfaces": "^3.0.19",
|
||||
"@push.rocks/consolecolor": "^2.0.2",
|
||||
"@push.rocks/isounique": "^1.0.4",
|
||||
"@push.rocks/smartclickhouse": "^2.0.17",
|
||||
"@push.rocks/smartfile": "^11.2.0",
|
||||
"@push.rocks/smarthash": "^3.0.4",
|
||||
"@push.rocks/smartpromise": "^4.2.3",
|
||||
"@push.rocks/smarttime": "^4.1.1",
|
||||
"@push.rocks/webrequest": "^3.0.37",
|
||||
"@tsclass/tsclass": "^9.2.0"
|
||||
},
|
||||
"files": [
|
||||
"ts/**/*",
|
||||
"ts_web/**/*",
|
||||
"dist/**/*",
|
||||
"dist_*/**/*",
|
||||
"dist_ts/**/*",
|
||||
"dist_ts_web/**/*",
|
||||
"assets/**/*",
|
||||
"cli.js",
|
||||
"npmextra.json",
|
||||
"readme.md"
|
||||
],
|
||||
"browserslist": [
|
||||
"last 1 chrome versions"
|
||||
],
|
||||
"type": "module",
|
||||
"homepage": "https://code.foss.global/push.rocks/smartlog#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://code.foss.global/push.rocks/smartlog.git"
|
||||
},
|
||||
"packageManager": "pnpm@10.10.0+sha512.d615db246fe70f25dcfea6d8d73dee782ce23e2245e3c4f6f888249fb568149318637dca73c2c5c8ef2a4ca0d5657fb9567188bfab47f566d1ee6ce987815c39",
|
||||
"bugs": {
|
||||
"url": "https://code.foss.global/push.rocks/smartlog/issues"
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {}
|
||||
}
|
||||
}
|
||||
|
9796
pnpm-lock.yaml
generated
Normal file
9796
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
53
readme.hints.md
Normal file
53
readme.hints.md
Normal file
@@ -0,0 +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
|
762
readme.md
762
readme.md
@@ -1,34 +1,748 @@
|
||||
# smartlog
|
||||
# @push.rocks/smartlog 🚀
|
||||
*The ultimate TypeScript logging solution for modern applications*
|
||||
|
||||
winston based logger for large scale projects
|
||||
[](https://www.npmjs.com/package/@push.rocks/smartlog)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
|
||||
## Availabililty
|
||||
> **smartlog** is a powerful, distributed, and extensible logging system designed for the cloud-native era. Whether you're debugging locally, monitoring production systems, or building complex microservices, smartlog adapts to your needs with style. 🎯
|
||||
|
||||
[](https://www.npmjs.com/package/smartlog)
|
||||
[](https://GitLab.com/pushrocks/smartlog)
|
||||
[](https://github.com/pushrocks/smartlog)
|
||||
[](https://pushrocks.gitlab.io/smartlog/)
|
||||
## 🌟 Why smartlog?
|
||||
|
||||
## Status for master
|
||||
- **🎨 Beautiful Console Output**: Color-coded, formatted logs that are actually readable
|
||||
- **🔌 Extensible Architecture**: Plug in any destination - databases, files, remote servers
|
||||
- **🌍 Distributed by Design**: Built for microservices with correlation and context tracking
|
||||
- **⚡ Zero-Config Start**: Works out of the box, scales when you need it
|
||||
- **🎭 Interactive CLI Tools**: Spinners and progress bars that handle non-TTY environments gracefully
|
||||
- **📊 Structured Logging**: JSON-based for easy parsing and analysis
|
||||
- **🔍 Smart Filtering**: Log levels and context-based filtering
|
||||
|
||||
[](https://GitLab.com/pushrocks/smartlog/commits/master)
|
||||
[](https://GitLab.com/pushrocks/smartlog/commits/master)
|
||||
[](https://www.npmjs.com/package/smartlog)
|
||||
[](https://david-dm.org/pushrocks/smartlog)
|
||||
[](https://www.bithound.io/github/pushrocks/smartlog/master/dependencies/npm)
|
||||
[](https://www.bithound.io/github/pushrocks/smartlog)
|
||||
[](https://snyk.io/test/npm/smartlog)
|
||||
[](https://nodejs.org/dist/latest-v6.x/docs/api/)
|
||||
[](https://nodejs.org/dist/latest-v6.x/docs/api/)
|
||||
[](http://standardjs.com/)
|
||||
## 📦 Installation
|
||||
|
||||
## Usage
|
||||
```bash
|
||||
# Using pnpm (recommended)
|
||||
pnpm add @push.rocks/smartlog
|
||||
|
||||
Use TypeScript for best in class instellisense.
|
||||
# Using npm
|
||||
npm install @push.rocks/smartlog
|
||||
|
||||
For further information read the linked docs at the top of this README.
|
||||
# Using yarn
|
||||
yarn add @push.rocks/smartlog
|
||||
```
|
||||
|
||||
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
|
||||
> | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)
|
||||
## 🚀 Quick Start
|
||||
|
||||
[](https://push.rocks)
|
||||
### Your First Logger
|
||||
|
||||
```typescript
|
||||
import { Smartlog } from '@push.rocks/smartlog';
|
||||
|
||||
// Create a logger with context
|
||||
const logger = new Smartlog({
|
||||
logContext: {
|
||||
company: 'MyStartup',
|
||||
companyunit: 'Backend Team',
|
||||
containerName: 'api-gateway',
|
||||
environment: 'production',
|
||||
runtime: 'node',
|
||||
zone: 'eu-central'
|
||||
}
|
||||
});
|
||||
|
||||
// Enable beautiful console output
|
||||
logger.enableConsole();
|
||||
|
||||
// Start logging!
|
||||
logger.log('info', '🎉 Application started successfully');
|
||||
logger.log('error', '💥 Database connection failed', {
|
||||
errorCode: 'DB_TIMEOUT',
|
||||
attemptCount: 3
|
||||
});
|
||||
```
|
||||
|
||||
### Using the Default Logger
|
||||
|
||||
For quick prototyping and simple applications:
|
||||
|
||||
```typescript
|
||||
import { defaultLogger } from '@push.rocks/smartlog';
|
||||
|
||||
defaultLogger.log('info', 'This is so easy!');
|
||||
```
|
||||
|
||||
## 📚 Core Concepts
|
||||
|
||||
### Log Levels
|
||||
|
||||
smartlog supports semantic log levels for different scenarios:
|
||||
|
||||
```typescript
|
||||
// Lifecycle events
|
||||
logger.log('lifecycle', '🔄 Container starting up...');
|
||||
|
||||
// Success states
|
||||
logger.log('success', '✅ Payment processed');
|
||||
logger.log('ok', '👍 Health check passed');
|
||||
|
||||
// Information and debugging
|
||||
logger.log('info', '📋 User profile updated');
|
||||
logger.log('note', '📌 Cache invalidated');
|
||||
logger.log('debug', '🔍 Query execution plan', { sql: 'SELECT * FROM users' });
|
||||
|
||||
// Warnings and errors
|
||||
logger.log('warn', '⚠️ Memory usage above 80%');
|
||||
logger.log('error', '❌ Failed to send email');
|
||||
|
||||
// Verbose output
|
||||
logger.log('silly', '🔬 Entering function processPayment()');
|
||||
```
|
||||
|
||||
### Log Groups for Correlation
|
||||
|
||||
Perfect for tracking request flows through your system:
|
||||
|
||||
```typescript
|
||||
// Track a user request through multiple operations
|
||||
const requestGroup = logger.createLogGroup('req-7f3a2b');
|
||||
|
||||
requestGroup.log('info', 'Received POST /api/users');
|
||||
requestGroup.log('debug', 'Validating request body');
|
||||
requestGroup.log('info', 'Creating user in database');
|
||||
requestGroup.log('success', 'User created successfully', { userId: 'usr_123' });
|
||||
|
||||
// All logs in the group share the same correlation ID
|
||||
```
|
||||
|
||||
## 🎯 Log Destinations
|
||||
|
||||
### Built-in Destinations
|
||||
|
||||
#### 🖥️ Local Console (Enhanced)
|
||||
|
||||
Beautiful, colored output for local development:
|
||||
|
||||
```typescript
|
||||
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
|
||||
|
||||
const localDestination = new DestinationLocal({
|
||||
logLevel: 'debug' // Optional: filter by minimum log level
|
||||
});
|
||||
|
||||
logger.addLogDestination(localDestination);
|
||||
```
|
||||
|
||||
#### 📁 File Logging
|
||||
|
||||
Persist logs to files with automatic rotation support:
|
||||
|
||||
```typescript
|
||||
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
|
||||
|
||||
const fileDestination = new SmartlogDestinationFile('./logs/app.log');
|
||||
logger.addLogDestination(fileDestination);
|
||||
```
|
||||
|
||||
#### 🌐 Browser DevTools
|
||||
|
||||
Optimized for browser environments with styled console output:
|
||||
|
||||
```typescript
|
||||
import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
|
||||
|
||||
const devtools = new SmartlogDestinationDevtools();
|
||||
logger.addLogDestination(devtools);
|
||||
```
|
||||
|
||||
#### 📊 ClickHouse Analytics
|
||||
|
||||
Store logs in ClickHouse for powerful analytics:
|
||||
|
||||
```typescript
|
||||
import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
|
||||
|
||||
const clickhouse = await SmartlogDestinationClickhouse.createAndStart({
|
||||
host: 'analytics.example.com',
|
||||
port: 8123,
|
||||
database: 'logs',
|
||||
user: 'logger',
|
||||
password: process.env.CLICKHOUSE_PASSWORD
|
||||
});
|
||||
|
||||
logger.addLogDestination(clickhouse);
|
||||
|
||||
// Query your logs with SQL!
|
||||
// SELECT * FROM logs WHERE level = 'error' AND timestamp > now() - INTERVAL 1 HOUR
|
||||
```
|
||||
|
||||
#### 🔗 Remote Receiver
|
||||
|
||||
Send logs to a centralized logging service:
|
||||
|
||||
```typescript
|
||||
import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
|
||||
|
||||
const receiver = new SmartlogDestinationReceiver({
|
||||
endpoint: 'https://logs.mycompany.com/ingest',
|
||||
apiKey: process.env.LOG_API_KEY,
|
||||
batchSize: 100, // Send logs in batches
|
||||
flushInterval: 5000 // Flush every 5 seconds
|
||||
});
|
||||
|
||||
logger.addLogDestination(receiver);
|
||||
```
|
||||
|
||||
### 🛠️ Custom Destinations
|
||||
|
||||
Build your own destination for any logging backend:
|
||||
|
||||
```typescript
|
||||
import { ILogDestination, ILogPackage } from '@push.rocks/smartlog/interfaces';
|
||||
|
||||
class ElasticsearchDestination implements ILogDestination {
|
||||
private client: ElasticsearchClient;
|
||||
|
||||
constructor(config: ElasticsearchConfig) {
|
||||
this.client = new ElasticsearchClient(config);
|
||||
}
|
||||
|
||||
async handleLog(logPackage: ILogPackage): Promise<void> {
|
||||
await this.client.index({
|
||||
index: `logs-${new Date().toISOString().split('T')[0]}`,
|
||||
body: {
|
||||
'@timestamp': logPackage.timestamp,
|
||||
level: logPackage.level,
|
||||
message: logPackage.message,
|
||||
context: logPackage.context,
|
||||
data: logPackage.data,
|
||||
correlation: logPackage.correlation
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Use your custom destination
|
||||
logger.addLogDestination(new ElasticsearchDestination({
|
||||
node: 'https://elasticsearch.example.com'
|
||||
}));
|
||||
```
|
||||
|
||||
## 🎨 Interactive Console Features
|
||||
|
||||
### Spinners
|
||||
|
||||
Create beautiful loading animations that degrade gracefully in CI/CD:
|
||||
|
||||
```typescript
|
||||
import { SmartlogSourceInteractive } from '@push.rocks/smartlog/source-interactive';
|
||||
|
||||
const spinner = new SmartlogSourceInteractive();
|
||||
|
||||
// Basic usage
|
||||
spinner.text('🔄 Fetching data from API...');
|
||||
// ... perform async operation
|
||||
spinner.finishSuccess('✅ Data fetched successfully!');
|
||||
|
||||
// Chained operations
|
||||
spinner
|
||||
.text('📡 Connecting to database')
|
||||
.successAndNext('🔍 Running migrations')
|
||||
.successAndNext('🌱 Seeding data')
|
||||
.finishSuccess('🎉 Database ready!');
|
||||
|
||||
// Customize appearance
|
||||
spinner
|
||||
.setSpinnerStyle('dots') // dots, line, star, simple
|
||||
.setColor('cyan') // any terminal color
|
||||
.setSpeed(80) // animation speed in ms
|
||||
.text('🚀 Deploying application...');
|
||||
|
||||
// Handle failures
|
||||
try {
|
||||
await deployApp();
|
||||
spinner.finishSuccess('✅ Deployed!');
|
||||
} catch (error) {
|
||||
spinner.finishFail('❌ Deployment failed');
|
||||
}
|
||||
```
|
||||
|
||||
### Progress Bars
|
||||
|
||||
Track long-running operations with style:
|
||||
|
||||
```typescript
|
||||
import { SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
|
||||
|
||||
// Create a progress bar
|
||||
const progress = new SmartlogProgressBar({
|
||||
total: 100,
|
||||
width: 40,
|
||||
complete: '█',
|
||||
incomplete: '░',
|
||||
showEta: true,
|
||||
showPercent: true,
|
||||
showCount: true
|
||||
});
|
||||
|
||||
// Update progress
|
||||
for (let i = 0; i <= 100; i++) {
|
||||
progress.update(i);
|
||||
await someAsyncWork();
|
||||
}
|
||||
|
||||
progress.complete();
|
||||
|
||||
// Real-world example: Processing files
|
||||
const files = await getFiles();
|
||||
const progress = new SmartlogProgressBar({
|
||||
total: files.length,
|
||||
width: 50
|
||||
});
|
||||
|
||||
for (const [index, file] of files.entries()) {
|
||||
await processFile(file);
|
||||
progress.increment(); // or progress.update(index + 1)
|
||||
}
|
||||
```
|
||||
|
||||
### Non-Interactive Fallback
|
||||
|
||||
Both spinners and progress bars automatically detect non-interactive environments (CI/CD, Docker logs, piped output) and fallback to simple text output:
|
||||
|
||||
```
|
||||
[Loading] Connecting to database
|
||||
[Success] Connected to database
|
||||
[Loading] Running migrations
|
||||
Progress: 25% (25/100)
|
||||
Progress: 50% (50/100)
|
||||
Progress: 100% (100/100)
|
||||
[Success] Migrations complete
|
||||
```
|
||||
|
||||
## 🔧 Advanced Features
|
||||
|
||||
### Context Management
|
||||
|
||||
Add context that flows through your entire application:
|
||||
|
||||
```typescript
|
||||
// Set global context
|
||||
logger.addLogContext({
|
||||
requestId: 'req-123',
|
||||
userId: 'user-456',
|
||||
feature: 'payment-processing'
|
||||
});
|
||||
|
||||
// All subsequent logs include this context
|
||||
logger.log('info', 'Processing payment');
|
||||
// Output includes: { ...context, message: 'Processing payment' }
|
||||
```
|
||||
|
||||
### Scoped Logging
|
||||
|
||||
Create scoped loggers for different components:
|
||||
|
||||
```typescript
|
||||
const dbLogger = logger.createScope('database');
|
||||
const apiLogger = logger.createScope('api');
|
||||
|
||||
dbLogger.log('info', 'Executing query');
|
||||
apiLogger.log('info', 'Handling request');
|
||||
// Logs include scope information for filtering
|
||||
```
|
||||
|
||||
### Minimum Log Levels
|
||||
|
||||
Control log verbosity per environment:
|
||||
|
||||
```typescript
|
||||
const logger = new Smartlog({
|
||||
logContext: { environment: 'production' },
|
||||
minimumLogLevel: 'warn' // Only warn and above in production
|
||||
});
|
||||
|
||||
// These won't be logged in production
|
||||
logger.log('debug', 'Detailed debug info');
|
||||
logger.log('info', 'Regular info');
|
||||
|
||||
// These will be logged
|
||||
logger.log('warn', 'Warning message');
|
||||
logger.log('error', 'Error message');
|
||||
```
|
||||
|
||||
### Increment Logging
|
||||
|
||||
Perfect for metrics and counters:
|
||||
|
||||
```typescript
|
||||
// Track API calls
|
||||
logger.increment('info', 'api.requests', { endpoint: '/users', method: 'GET' });
|
||||
logger.increment('info', 'api.requests', { endpoint: '/users', method: 'POST' });
|
||||
|
||||
// Track errors by type
|
||||
logger.increment('error', 'payment.failed', { reason: 'insufficient_funds' });
|
||||
logger.increment('error', 'payment.failed', { reason: 'card_declined' });
|
||||
```
|
||||
|
||||
### Capture All Console Output
|
||||
|
||||
Redirect all console.log and console.error through smartlog:
|
||||
|
||||
```typescript
|
||||
logger.enableConsole({
|
||||
captureAll: true // Capture all console.* methods
|
||||
});
|
||||
|
||||
console.log('This goes through smartlog!');
|
||||
console.error('This too!');
|
||||
// All console output is now structured and routed through your destinations
|
||||
```
|
||||
|
||||
## 🏗️ Real-World Examples
|
||||
|
||||
### Microservice with Distributed Tracing
|
||||
|
||||
```typescript
|
||||
import { Smartlog } from '@push.rocks/smartlog';
|
||||
import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
|
||||
|
||||
// Initialize logger with service context
|
||||
const logger = new Smartlog({
|
||||
logContext: {
|
||||
company: 'TechCorp',
|
||||
companyunit: 'Platform',
|
||||
containerName: 'user-service',
|
||||
environment: process.env.NODE_ENV,
|
||||
runtime: 'node',
|
||||
zone: process.env.CLOUD_ZONE
|
||||
}
|
||||
});
|
||||
|
||||
// Add ClickHouse for analytics
|
||||
const clickhouse = await SmartlogDestinationClickhouse.createAndStart({
|
||||
host: process.env.CLICKHOUSE_HOST,
|
||||
database: 'microservices_logs'
|
||||
});
|
||||
logger.addLogDestination(clickhouse);
|
||||
|
||||
// Enable local console for development
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
logger.enableConsole();
|
||||
}
|
||||
|
||||
// Express middleware for request tracking
|
||||
app.use((req, res, next) => {
|
||||
const requestId = generateRequestId();
|
||||
const logGroup = logger.createLogGroup(requestId);
|
||||
|
||||
// Attach logger to request
|
||||
req.logger = logGroup;
|
||||
|
||||
// Log request
|
||||
logGroup.log('info', 'Incoming request', {
|
||||
method: req.method,
|
||||
path: req.path,
|
||||
ip: req.ip
|
||||
});
|
||||
|
||||
// Track response
|
||||
res.on('finish', () => {
|
||||
logGroup.log('info', 'Request completed', {
|
||||
statusCode: res.statusCode,
|
||||
duration: Date.now() - req.startTime
|
||||
});
|
||||
});
|
||||
|
||||
next();
|
||||
});
|
||||
```
|
||||
|
||||
### CLI Tool with Progress Tracking
|
||||
|
||||
```typescript
|
||||
import { Smartlog } from '@push.rocks/smartlog';
|
||||
import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
|
||||
|
||||
const logger = new Smartlog({
|
||||
logContext: {
|
||||
containerName: 'migration-tool',
|
||||
environment: 'cli'
|
||||
}
|
||||
});
|
||||
|
||||
logger.enableConsole();
|
||||
|
||||
async function migrateDatabase() {
|
||||
const spinner = new SmartlogSourceInteractive();
|
||||
|
||||
// Connect to database
|
||||
spinner.text('🔌 Connecting to database...');
|
||||
await connectDB();
|
||||
spinner.finishSuccess('✅ Connected to database');
|
||||
|
||||
// Get migrations
|
||||
spinner.text('📋 Loading migrations...');
|
||||
const migrations = await getMigrations();
|
||||
spinner.finishSuccess(`✅ Found ${migrations.length} migrations`);
|
||||
|
||||
// Run migrations with progress bar
|
||||
const progress = new SmartlogProgressBar({
|
||||
total: migrations.length,
|
||||
width: 40,
|
||||
showEta: true
|
||||
});
|
||||
|
||||
for (const [index, migration] of migrations.entries()) {
|
||||
logger.log('info', `Running migration: ${migration.name}`);
|
||||
await runMigration(migration);
|
||||
progress.update(index + 1);
|
||||
}
|
||||
|
||||
progress.complete();
|
||||
logger.log('success', '🎉 All migrations completed successfully!');
|
||||
}
|
||||
```
|
||||
|
||||
### Production Logging with Multiple Destinations
|
||||
|
||||
```typescript
|
||||
import { Smartlog } from '@push.rocks/smartlog';
|
||||
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
|
||||
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
|
||||
import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
|
||||
|
||||
const logger = new Smartlog({
|
||||
logContext: {
|
||||
company: 'Enterprise Corp',
|
||||
containerName: 'payment-processor',
|
||||
environment: 'production',
|
||||
runtime: 'node',
|
||||
zone: 'us-east-1'
|
||||
},
|
||||
minimumLogLevel: 'info' // No debug logs in production
|
||||
});
|
||||
|
||||
// Console for container logs (structured for log aggregators)
|
||||
logger.addLogDestination(new DestinationLocal());
|
||||
|
||||
// File for audit trail
|
||||
logger.addLogDestination(new SmartlogDestinationFile('/var/log/app/audit.log'));
|
||||
|
||||
// Central logging service
|
||||
logger.addLogDestination(new SmartlogDestinationReceiver({
|
||||
endpoint: 'https://logs.enterprise.com/ingest',
|
||||
apiKey: process.env.LOG_API_KEY,
|
||||
batchSize: 100,
|
||||
flushInterval: 5000
|
||||
}));
|
||||
|
||||
// Critical error alerts
|
||||
logger.addLogDestination({
|
||||
async handleLog(logPackage) {
|
||||
if (logPackage.level === 'error' && logPackage.data?.critical) {
|
||||
await sendAlert({
|
||||
channel: 'ops-team',
|
||||
message: `🚨 Critical error: ${logPackage.message}`,
|
||||
data: logPackage
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 🔌 Integration with Other Tools
|
||||
|
||||
### PM2 Integration
|
||||
|
||||
```typescript
|
||||
// ecosystem.config.js
|
||||
module.exports = {
|
||||
apps: [{
|
||||
name: 'api',
|
||||
script: './dist/index.js',
|
||||
error_file: '/dev/null', // Disable PM2 error log
|
||||
out_file: '/dev/null', // Disable PM2 out log
|
||||
merge_logs: true,
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
// smartlog handles all logging
|
||||
}
|
||||
}]
|
||||
};
|
||||
```
|
||||
|
||||
### Docker Integration
|
||||
|
||||
```dockerfile
|
||||
FROM node:18-alpine
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN pnpm install --production
|
||||
|
||||
# smartlog handles structured logging
|
||||
# No need for special log drivers
|
||||
CMD ["node", "dist/index.js"]
|
||||
```
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml
|
||||
services:
|
||||
app:
|
||||
build: .
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
# Logs are structured JSON, perfect for log aggregators
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
```
|
||||
|
||||
## 🏆 Best Practices
|
||||
|
||||
### 1. Use Semantic Log Levels
|
||||
|
||||
```typescript
|
||||
// ✅ Good - semantic and meaningful
|
||||
logger.log('lifecycle', 'Server starting on port 3000');
|
||||
logger.log('success', 'Database connection established');
|
||||
logger.log('error', 'Failed to process payment', { orderId, error });
|
||||
|
||||
// ❌ Bad - everything is 'info'
|
||||
logger.log('info', 'Server starting');
|
||||
logger.log('info', 'Database connected');
|
||||
logger.log('info', 'Error: payment failed');
|
||||
```
|
||||
|
||||
### 2. Include Structured Data
|
||||
|
||||
```typescript
|
||||
// ✅ Good - structured data for analysis
|
||||
logger.log('error', 'API request failed', {
|
||||
endpoint: '/api/users',
|
||||
statusCode: 500,
|
||||
duration: 1234,
|
||||
userId: 'usr_123',
|
||||
errorCode: 'INTERNAL_ERROR'
|
||||
});
|
||||
|
||||
// ❌ Bad - data embedded in message
|
||||
logger.log('error', `API request to /api/users failed with 500 in 1234ms for user usr_123`);
|
||||
```
|
||||
|
||||
### 3. Use Log Groups for Correlation
|
||||
|
||||
```typescript
|
||||
// ✅ Good - correlated logs
|
||||
async function processOrder(orderId: string) {
|
||||
const logGroup = logger.createLogGroup(orderId);
|
||||
|
||||
logGroup.log('info', 'Processing order');
|
||||
logGroup.log('debug', 'Validating items');
|
||||
logGroup.log('info', 'Charging payment');
|
||||
logGroup.log('success', 'Order processed');
|
||||
}
|
||||
|
||||
// ❌ Bad - no correlation
|
||||
async function processOrder(orderId: string) {
|
||||
logger.log('info', `Processing order ${orderId}`);
|
||||
logger.log('debug', `Validating items for ${orderId}`);
|
||||
logger.log('info', `Charging payment for ${orderId}`);
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Environment-Specific Configuration
|
||||
|
||||
```typescript
|
||||
// ✅ Good - different configs per environment
|
||||
const logger = new Smartlog({
|
||||
logContext: {
|
||||
environment: process.env.NODE_ENV,
|
||||
// ... other context
|
||||
},
|
||||
minimumLogLevel: process.env.NODE_ENV === 'production' ? 'info' : 'silly'
|
||||
});
|
||||
|
||||
// Add destinations based on environment
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
logger.addLogDestination(clickhouseDestination);
|
||||
logger.addLogDestination(alertingDestination);
|
||||
} else {
|
||||
logger.enableConsole();
|
||||
}
|
||||
```
|
||||
|
||||
## 📖 API Reference
|
||||
|
||||
### Smartlog Class
|
||||
|
||||
```typescript
|
||||
class Smartlog {
|
||||
constructor(options?: ISmartlogOptions)
|
||||
|
||||
// Logging methods
|
||||
log(level: TLogLevel, message: string, data?: any, correlation?: ILogCorrelation): void
|
||||
increment(level: TLogLevel, key: string, data?: any): void
|
||||
|
||||
// Configuration
|
||||
enableConsole(options?: IConsoleOptions): void
|
||||
addLogDestination(destination: ILogDestination): void
|
||||
addLogContext(context: Partial<ILogContext>): void
|
||||
|
||||
// Log groups
|
||||
createLogGroup(transactionId?: string): LogGroup
|
||||
createScope(scopeName: string): Smartlog
|
||||
}
|
||||
```
|
||||
|
||||
### Log Levels
|
||||
|
||||
```typescript
|
||||
type TLogLevel =
|
||||
| 'silly' // Very verbose debugging
|
||||
| 'debug' // Debug information
|
||||
| 'info' // Informational messages
|
||||
| 'note' // Notable events
|
||||
| 'ok' // Success confirmation
|
||||
| 'success' // Major success
|
||||
| 'warn' // Warning messages
|
||||
| 'error' // Error messages
|
||||
| 'lifecycle' // Application lifecycle events
|
||||
```
|
||||
|
||||
### Log Package Structure
|
||||
|
||||
```typescript
|
||||
interface ILogPackage {
|
||||
timestamp: number;
|
||||
level: TLogLevel;
|
||||
message: string;
|
||||
data?: any;
|
||||
context: ILogContext;
|
||||
correlation?: ILogCorrelation;
|
||||
}
|
||||
```
|
||||
|
||||
For complete API documentation, see [API.md](API.md).
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
|
||||
|
||||
## 📄 License and Legal Information
|
||||
|
||||
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||
|
||||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||
|
||||
### Trademarks
|
||||
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
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.
|
101
readme.plan.md
Normal file
101
readme.plan.md
Normal 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
|
48
test/test.browser.ts
Normal file
48
test/test.browser.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartlog from '../ts/index.js';
|
||||
|
||||
let testConsoleLog: smartlog.ConsoleLog;
|
||||
let testSmartLog: smartlog.Smartlog;
|
||||
|
||||
tap.test('should produce a valid ConsoleLog instance', async () => {
|
||||
testConsoleLog = new smartlog.ConsoleLog();
|
||||
testConsoleLog.log('ok', 'this is ok');
|
||||
});
|
||||
|
||||
tap.test('should produce instance of Smartlog', async () => {
|
||||
testSmartLog = new smartlog.Smartlog({
|
||||
logContext: {
|
||||
environment: 'test',
|
||||
runtime: 'node',
|
||||
zone: 'gitzone',
|
||||
company: 'Lossless GmbH',
|
||||
companyunit: 'Lossless Cloud',
|
||||
containerName: 'testing',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should enable console logging', async () => {
|
||||
testSmartLog.enableConsole({
|
||||
captureAll: true,
|
||||
});
|
||||
console.log('this is a normal log that should be captured');
|
||||
console.log(new Error('hi there'));
|
||||
testSmartLog.log('info', 'this should only be printed once');
|
||||
});
|
||||
|
||||
tap.test('should be able to log things', async () => {
|
||||
testSmartLog.log('silly', 'hi');
|
||||
});
|
||||
|
||||
tap.test('should create a log group', async () => {
|
||||
const logGroup = testSmartLog.createLogGroup('some cool transaction');
|
||||
logGroup.log('info', 'this is logged from a log group');
|
||||
});
|
||||
|
||||
tap.test('should catch error', async () => {
|
||||
console.error(new Error('hey'));
|
||||
// throw new Error('hey');
|
||||
});
|
||||
|
||||
export default tap.start();
|
9
test/test.context.ts
Normal file
9
test/test.context.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
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 () => {
|
||||
expect(typeof smartlogContext.standardExport).toEqual('string');
|
||||
expect(smartlogContext.standardExport).toEqual('Hi there! :) This is an exported string');
|
||||
});
|
||||
|
||||
export default tap.start();
|
19
test/test.destination-clickhouse.node.ts
Normal file
19
test/test.destination-clickhouse.node.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import { SmartlogDestinationClickhouse } from '../ts_destination_clickhouse/index.js';
|
||||
import * as smartclickhouse from '@push.rocks/smartclickhouse';
|
||||
|
||||
// Test we can create a destination instance
|
||||
tap.test('should create a ClickHouse destination instance', async () => {
|
||||
// Use mock configuration
|
||||
const clickhouseOptions: smartclickhouse.IClickhouseConstructorOptions = {
|
||||
url: 'defult:@localhost:8123',
|
||||
database: 'test_logs'
|
||||
};
|
||||
|
||||
// Verify we can create an instance
|
||||
// We won't start it to avoid making real connections
|
||||
const clickhouseDestination = new SmartlogDestinationClickhouse(clickhouseOptions);
|
||||
expect(clickhouseDestination).toBeTruthy();
|
||||
});
|
||||
|
||||
export default tap.start();
|
13
test/test.destination-devtools.browser.ts
Normal file
13
test/test.destination-devtools.browser.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import { SmartlogDestinationDevtools } from '../ts_destination_devtools/index.js';
|
||||
|
||||
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();
|
||||
};
|
||||
|
||||
export default run();
|
10
test/test.destination-devtools.node.ts
Normal file
10
test/test.destination-devtools.node.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import { SmartlogDestinationDevtools } from '../ts_destination_devtools/index.js';
|
||||
|
||||
// Test we can create a destination instance
|
||||
tap.test('should create a DevTools destination instance', async () => {
|
||||
const devtoolsDestination = new SmartlogDestinationDevtools();
|
||||
expect(devtoolsDestination).toBeTruthy();
|
||||
});
|
||||
|
||||
export default tap.start();
|
87
test/test.destination-file.node.ts
Normal file
87
test/test.destination-file.node.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
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';
|
||||
import * as os from 'os';
|
||||
|
||||
let testLogDir: string;
|
||||
let testLogFile: string;
|
||||
let testDestination: SmartlogDestinationFile;
|
||||
|
||||
// Setup and teardown helpers
|
||||
const createTempLogDir = () => {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smartlog-test-'));
|
||||
return tempDir;
|
||||
};
|
||||
|
||||
const removeTempDir = (dirPath: string) => {
|
||||
if (fs.existsSync(dirPath)) {
|
||||
const files = fs.readdirSync(dirPath);
|
||||
for (const file of files) {
|
||||
fs.unlinkSync(path.join(dirPath, file));
|
||||
}
|
||||
fs.rmdirSync(dirPath);
|
||||
}
|
||||
};
|
||||
|
||||
// Tests
|
||||
tap.test('should prepare test environment', async () => {
|
||||
testLogDir = createTempLogDir();
|
||||
testLogFile = path.join(testLogDir, 'test.log');
|
||||
expect(fs.existsSync(testLogDir)).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('should create a file destination instance with a valid path', async () => {
|
||||
testDestination = new SmartlogDestinationFile(testLogFile);
|
||||
expect(testDestination).toBeTruthy();
|
||||
expect(fs.existsSync(testLogFile)).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('should throw error when file path is not absolute', async () => {
|
||||
let errorThrown = false;
|
||||
try {
|
||||
new SmartlogDestinationFile('relative/path/file.log');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
expect(error.message).toContain('filePath needs to be absolute');
|
||||
}
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('should write log messages to file', async () => {
|
||||
const testMessage = 'Test log message';
|
||||
|
||||
await testDestination.handleLog({
|
||||
timestamp: Date.now(),
|
||||
type: 'log',
|
||||
level: 'info',
|
||||
message: testMessage,
|
||||
context: {
|
||||
environment: 'test',
|
||||
runtime: 'node'
|
||||
},
|
||||
correlation: {
|
||||
id: '123',
|
||||
type: 'none'
|
||||
}
|
||||
});
|
||||
|
||||
// Give file system a moment to write
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
|
||||
const fileContent = fs.readFileSync(testLogFile, 'utf8');
|
||||
expect(fileContent).toContain(testMessage);
|
||||
});
|
||||
|
||||
tap.test('should clean up test resources', async () => {
|
||||
// Close file handle before cleanup
|
||||
testDestination.fileWriteStream.end();
|
||||
|
||||
// Small delay to ensure file is properly closed
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
removeTempDir(testLogDir);
|
||||
expect(fs.existsSync(testLogDir)).toBeFalse();
|
||||
});
|
||||
|
||||
export default tap.start();
|
114
test/test.destination-local.node.ts
Normal file
114
test/test.destination-local.node.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import { DestinationLocal } from '../ts_destination_local/index.js';
|
||||
import * as smartlogInterfaces from '../ts_interfaces/index.js';
|
||||
|
||||
let testDestination: DestinationLocal;
|
||||
|
||||
// Mock log package
|
||||
const createMockLogPackage = (level: smartlogInterfaces.TLogLevel, message: string): smartlogInterfaces.ILogPackage => {
|
||||
return {
|
||||
timestamp: Date.now(),
|
||||
type: 'log',
|
||||
level,
|
||||
message,
|
||||
context: {
|
||||
environment: 'test',
|
||||
runtime: 'node'
|
||||
},
|
||||
correlation: {
|
||||
id: '123',
|
||||
type: 'none'
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Tests
|
||||
tap.test('should create a local destination instance', async () => {
|
||||
testDestination = new DestinationLocal();
|
||||
expect(testDestination).toBeTruthy();
|
||||
});
|
||||
|
||||
tap.test('should handle logs with different levels', async () => {
|
||||
// Testing with a spy would be ideal, but since we don't have a mocking framework,
|
||||
// we'll just verify the method runs without errors for different log levels
|
||||
|
||||
// Test info level
|
||||
const logPackageInfo = createMockLogPackage('info', 'Info message');
|
||||
await testDestination.handleLog(logPackageInfo);
|
||||
|
||||
// Test error level
|
||||
const logPackageError = createMockLogPackage('error', 'Error message');
|
||||
await testDestination.handleLog(logPackageError);
|
||||
|
||||
// Test warn level
|
||||
const logPackageWarn = createMockLogPackage('warn', 'Warning message');
|
||||
await testDestination.handleLog(logPackageWarn);
|
||||
|
||||
// Test silly level
|
||||
const logPackageSilly = createMockLogPackage('silly', 'Silly message');
|
||||
await testDestination.handleLog(logPackageSilly);
|
||||
});
|
||||
|
||||
tap.test('should handle reduced logging', async () => {
|
||||
testDestination = new DestinationLocal();
|
||||
|
||||
// Note: In a real test environment with a mocking framework,
|
||||
// we would capture console output and verify it's only written
|
||||
// according to the expected behavior. Here we just ensure
|
||||
// the methods execute without errors.
|
||||
|
||||
// First call with message
|
||||
testDestination.logReduced('Test message');
|
||||
|
||||
// Same message immediately after
|
||||
testDestination.logReduced('Test message');
|
||||
|
||||
// Different message
|
||||
testDestination.logReduced('Different message');
|
||||
});
|
||||
|
||||
tap.test('should handle repeated logging with repeatEveryTimesArg', async () => {
|
||||
testDestination = new DestinationLocal();
|
||||
|
||||
// First call with message
|
||||
testDestination.logReduced('Repeated with count', 3);
|
||||
|
||||
// Second call
|
||||
testDestination.logReduced('Repeated with count', 3);
|
||||
|
||||
// Third call
|
||||
testDestination.logReduced('Repeated with count', 3);
|
||||
|
||||
// Fourth call (3rd repetition)
|
||||
testDestination.logReduced('Repeated with count', 3);
|
||||
});
|
||||
|
||||
tap.test('should create new line(s)', async () => {
|
||||
testDestination = new DestinationLocal();
|
||||
|
||||
// Default 1 line
|
||||
testDestination.newLine();
|
||||
|
||||
// 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();
|
72
test/test.destination-receiver.node.ts
Normal file
72
test/test.destination-receiver.node.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
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';
|
||||
|
||||
let testDestination: SmartlogDestinationReceiver;
|
||||
let testSmartlog: Smartlog;
|
||||
|
||||
// Mock log package
|
||||
const createMockLogPackage = (level: smartlogInterfaces.TLogLevel, message: string): smartlogInterfaces.ILogPackage => {
|
||||
return {
|
||||
timestamp: Date.now(),
|
||||
type: 'log',
|
||||
level,
|
||||
message,
|
||||
context: {
|
||||
environment: 'test',
|
||||
runtime: 'node'
|
||||
},
|
||||
correlation: {
|
||||
id: '123',
|
||||
type: 'none'
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Tests
|
||||
tap.test('should create a Smartlog instance', async () => {
|
||||
testSmartlog = new Smartlog({
|
||||
logContext: {
|
||||
environment: 'test',
|
||||
runtime: 'node',
|
||||
zone: 'test-zone',
|
||||
company: 'Test Company',
|
||||
companyunit: 'Test Unit',
|
||||
containerName: 'test-container',
|
||||
},
|
||||
});
|
||||
|
||||
expect(testSmartlog).toBeTruthy();
|
||||
});
|
||||
|
||||
tap.test('should create a destination receiver instance with valid options', async () => {
|
||||
testDestination = new SmartlogDestinationReceiver({
|
||||
passphrase: 'test-passphrase',
|
||||
receiverEndpoint: 'https://example.com/logs',
|
||||
});
|
||||
|
||||
expect(testDestination).toBeTruthy();
|
||||
});
|
||||
|
||||
tap.test('should attempt to send logs to the receiver endpoint', async () => {
|
||||
// Create a mock version of the webrequest.postJson method to avoid actual HTTP calls
|
||||
const originalPostJson = testDestination['webrequest'].postJson;
|
||||
testDestination['webrequest'].postJson = async () => {
|
||||
return {
|
||||
body: { status: 'ok' },
|
||||
statusCode: 200
|
||||
};
|
||||
};
|
||||
|
||||
try {
|
||||
const logPackage = createMockLogPackage('info', 'Test receiver message');
|
||||
const result = await testDestination.handleLog(logPackage);
|
||||
expect(result).toEqual({ status: 'ok' });
|
||||
} finally {
|
||||
// Restore the original method
|
||||
testDestination['webrequest'].postJson = originalPostJson;
|
||||
}
|
||||
});
|
||||
|
||||
export default tap.start();
|
64
test/test.noninteractive.node.ts
Normal file
64
test/test.noninteractive.node.ts
Normal 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();
|
115
test/test.receiver.node.ts
Normal file
115
test/test.receiver.node.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import { SmartlogReceiver } from '../ts_receiver/index.js';
|
||||
import { Smartlog } from '../dist_ts/index.js';
|
||||
import * as smartlogInterfaces from '../ts_interfaces/index.js';
|
||||
import * as smarthash from '@push.rocks/smarthash';
|
||||
|
||||
let testSmartlog: Smartlog;
|
||||
let testReceiver: SmartlogReceiver;
|
||||
const testPassphrase = 'test-secret-passphrase';
|
||||
|
||||
// Helper to create authenticated log package
|
||||
const createAuthenticatedLogPackage = (
|
||||
level: smartlogInterfaces.TLogLevel,
|
||||
message: string
|
||||
): smartlogInterfaces.ILogPackageAuthenticated => {
|
||||
const logPackage: smartlogInterfaces.ILogPackage = {
|
||||
timestamp: Date.now(),
|
||||
type: 'log',
|
||||
level,
|
||||
message,
|
||||
context: {
|
||||
environment: 'test',
|
||||
runtime: 'node'
|
||||
},
|
||||
correlation: {
|
||||
id: '123',
|
||||
type: 'none'
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
auth: smarthash.sha256FromStringSync(testPassphrase),
|
||||
logPackage
|
||||
};
|
||||
};
|
||||
|
||||
// Tests
|
||||
tap.test('should create a Smartlog instance for receiver', async () => {
|
||||
testSmartlog = new Smartlog({
|
||||
logContext: {
|
||||
environment: 'test',
|
||||
runtime: 'node',
|
||||
zone: 'test-zone',
|
||||
company: 'Test Company',
|
||||
companyunit: 'Test Unit',
|
||||
containerName: 'test-container',
|
||||
},
|
||||
});
|
||||
|
||||
expect(testSmartlog).toBeTruthy();
|
||||
});
|
||||
|
||||
tap.test('should create a SmartlogReceiver instance', async () => {
|
||||
// Create a validator function that always returns true
|
||||
const validatorFunction = async () => true;
|
||||
|
||||
testReceiver = new SmartlogReceiver({
|
||||
smartlogInstance: testSmartlog,
|
||||
passphrase: testPassphrase,
|
||||
validatorFunction
|
||||
});
|
||||
|
||||
expect(testReceiver).toBeTruthy();
|
||||
expect(testReceiver.passphrase).toEqual(testPassphrase);
|
||||
});
|
||||
|
||||
tap.test('should handle authenticated log with correct passphrase', async () => {
|
||||
const authLogPackage = createAuthenticatedLogPackage('info', 'Test authenticated message');
|
||||
|
||||
const result = await testReceiver.handleAuthenticatedLog(authLogPackage);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result.status).toEqual('ok');
|
||||
});
|
||||
|
||||
tap.test('should reject authenticated log with incorrect passphrase', async () => {
|
||||
const logPackage: smartlogInterfaces.ILogPackage = {
|
||||
timestamp: Date.now(),
|
||||
type: 'log',
|
||||
level: 'info',
|
||||
message: 'Test unauthorized message',
|
||||
context: {
|
||||
environment: 'test',
|
||||
runtime: 'node'
|
||||
},
|
||||
correlation: {
|
||||
id: '123',
|
||||
type: 'none'
|
||||
}
|
||||
};
|
||||
|
||||
const badAuthPackage = {
|
||||
auth: 'incorrect-hash',
|
||||
logPackage
|
||||
};
|
||||
|
||||
const result = await testReceiver.handleAuthenticatedLog(badAuthPackage);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result.status).toEqual('error');
|
||||
});
|
||||
|
||||
tap.test('should handle many authenticated logs', async () => {
|
||||
const authLogPackage1 = createAuthenticatedLogPackage('info', 'Test batch message 1');
|
||||
const authLogPackage2 = createAuthenticatedLogPackage('warn', 'Test batch message 2');
|
||||
const authLogPackage3 = createAuthenticatedLogPackage('error', 'Test batch message 3');
|
||||
|
||||
const authLogPackages = [authLogPackage1, authLogPackage2, authLogPackage3];
|
||||
|
||||
await testReceiver.handleManyAuthenticatedLogs(authLogPackages);
|
||||
|
||||
// No assertions needed as we're just testing it doesn't throw errors
|
||||
});
|
||||
|
||||
export default tap.start();
|
190
test/test.source-interactive.node.ts
Normal file
190
test/test.source-interactive.node.ts
Normal 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();
|
45
test/test.ts
45
test/test.ts
@@ -1,19 +1,48 @@
|
||||
import { expect, tap } from 'tapbundle';
|
||||
import * as smartlog from '../ts/index';
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartlog from '../ts/index.js';
|
||||
|
||||
let defaultLogger: smartlog.Smartlog;
|
||||
let testConsoleLog: smartlog.ConsoleLog;
|
||||
let testSmartLog: smartlog.Smartlog;
|
||||
|
||||
tap.test('should produce a valid ConsoleLog instance', async () => {
|
||||
testConsoleLog = new smartlog.ConsoleLog();
|
||||
testConsoleLog.log('ok', 'this is ok');
|
||||
});
|
||||
|
||||
tap.test('should produce instance of Smartlog', async () => {
|
||||
defaultLogger = smartlog.getDefaultLogger();
|
||||
expect(defaultLogger).to.be.instanceOf(smartlog.Smartlog);
|
||||
testSmartLog = new smartlog.Smartlog({
|
||||
logContext: {
|
||||
environment: 'test',
|
||||
runtime: 'node',
|
||||
zone: 'gitzone',
|
||||
company: 'Lossless GmbH',
|
||||
companyunit: 'Lossless Cloud',
|
||||
containerName: 'testing',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should enable console logging', async () => {
|
||||
defaultLogger.enableConsole();
|
||||
testSmartLog.enableConsole({
|
||||
captureAll: true,
|
||||
});
|
||||
console.log('this is a normal log that should be captured');
|
||||
console.log(new Error('hi there'));
|
||||
testSmartLog.log('info', 'this should only be printed once');
|
||||
});
|
||||
|
||||
tap.test('should be able to log things', async () => {
|
||||
defaultLogger.log('silly', 'hi');
|
||||
testSmartLog.log('silly', 'hi');
|
||||
});
|
||||
|
||||
tap.start();
|
||||
tap.test('should create a log group', async () => {
|
||||
const logGroup = testSmartLog.createLogGroup('some cool transaction');
|
||||
logGroup.log('info', 'this is logged from a log group');
|
||||
});
|
||||
|
||||
tap.test('should catch error', async () => {
|
||||
console.error(new Error('hey'));
|
||||
// throw new Error('hey');
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
|
8
ts/00_commitinfo_data.ts
Normal file
8
ts/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartlog',
|
||||
version: '3.1.9',
|
||||
description: 'A minimalistic, distributed, and extensible logging tool supporting centralized log management.'
|
||||
}
|
17
ts/index.ts
17
ts/index.ts
@@ -1,13 +1,6 @@
|
||||
import * as plugins from './smartlog.plugins';
|
||||
import { Smartlog } from './smartlog.classes.smartlog';
|
||||
import * as plugins from './smartlog.plugins.js';
|
||||
import { ConsoleLog } from './smartlog.classes.consolelog.js';
|
||||
import { LogGroup } from './smartlog.classes.loggroup.js';
|
||||
import { Smartlog } from './smartlog.classes.smartlog.js';
|
||||
|
||||
export { Smartlog };
|
||||
|
||||
let defaultLogger: Smartlog;
|
||||
|
||||
export const getDefaultLogger = () => {
|
||||
if (!defaultLogger) {
|
||||
defaultLogger = new Smartlog();
|
||||
}
|
||||
return defaultLogger;
|
||||
};
|
||||
export { ConsoleLog, LogGroup, Smartlog };
|
||||
|
15
ts/smartlog.classes.consolelog.ts
Normal file
15
ts/smartlog.classes.consolelog.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import * as plugins from './smartlog.plugins.js';
|
||||
|
||||
/**
|
||||
* a console log optimized for smartlog
|
||||
*/
|
||||
export class ConsoleLog {
|
||||
public log(
|
||||
logLevelArg: plugins.smartlogInterfaces.TLogLevel,
|
||||
logMessageArg: string,
|
||||
dataArg?: any,
|
||||
correlationArg?: plugins.smartlogInterfaces.ILogCorrelation,
|
||||
) {
|
||||
console.log(`__# ${logLevelArg}: ${logMessageArg}`);
|
||||
}
|
||||
}
|
27
ts/smartlog.classes.loggroup.ts
Normal file
27
ts/smartlog.classes.loggroup.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import * as plugins from './smartlog.plugins.js';
|
||||
import { Smartlog } from './smartlog.classes.smartlog.js';
|
||||
|
||||
export class LogGroup {
|
||||
public smartlogRef: Smartlog;
|
||||
public transactionId: string;
|
||||
public groupId = plugins.isounique.uni();
|
||||
|
||||
constructor(smartlogInstance: Smartlog, transactionIdArg: string) {
|
||||
this.smartlogRef = smartlogInstance;
|
||||
this.transactionId = transactionIdArg;
|
||||
}
|
||||
|
||||
public log(
|
||||
logLevelArg: plugins.smartlogInterfaces.TLogLevel,
|
||||
logMessageArg: string,
|
||||
logDataArg?: any,
|
||||
) {
|
||||
this.smartlogRef.log(logLevelArg, logMessageArg, logDataArg, {
|
||||
id: plugins.isounique.uni(),
|
||||
type: 'none',
|
||||
group: this.groupId,
|
||||
instance: this.smartlogRef.uniInstanceId,
|
||||
transaction: this.transactionId,
|
||||
});
|
||||
}
|
||||
}
|
@@ -1,10 +1,21 @@
|
||||
import * as plugins from './smartlog.plugins';
|
||||
|
||||
import { ILogDestination } from 'smartlog-interfaces';
|
||||
import * as plugins from './smartlog.plugins.js';
|
||||
|
||||
export class LogRouter {
|
||||
logDestinations: ILogDestination[] = [];
|
||||
/**
|
||||
* all log destinations
|
||||
*/
|
||||
private logDestinations: plugins.smartlogInterfaces.ILogDestination[] = [];
|
||||
|
||||
constructor() {}
|
||||
|
||||
addLogDestination;
|
||||
public addLogDestination(logDestination: plugins.smartlogInterfaces.ILogDestination) {
|
||||
this.logDestinations.push(logDestination);
|
||||
}
|
||||
|
||||
// routes the log according to added logDestinations
|
||||
public async routeLog(logPackageArg: plugins.smartlogInterfaces.ILogPackage) {
|
||||
for (const logDestination of this.logDestinations) {
|
||||
await logDestination.handleLog(logPackageArg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,13 +1,44 @@
|
||||
import * as plugins from './smartlog.plugins';
|
||||
import * as plugins from './smartlog.plugins.js';
|
||||
|
||||
// interfaces
|
||||
import { TEnvironment, ILogContext, TLogLevel, TRuntime } from 'smartlog-interfaces';
|
||||
import { LogRouter } from './smartlog.classes.logrouter.js';
|
||||
import { LogGroup } from './smartlog.classes.loggroup.js';
|
||||
|
||||
export interface ISmartlogContructorOptions {
|
||||
logContext: plugins.smartlogInterfaces.ILogContext;
|
||||
minimumLogLevel?: plugins.smartlogInterfaces.TLogLevel;
|
||||
}
|
||||
|
||||
export class Smartlog implements plugins.smartlogInterfaces.ILogDestination {
|
||||
// STATIC
|
||||
public static createForCommitinfo(
|
||||
commitinfo: plugins.smartlogInterfaces.ILogContext['commitinfo'],
|
||||
) {
|
||||
return new Smartlog({
|
||||
logContext: {
|
||||
commitinfo,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// INSTANCE
|
||||
public logContext: plugins.smartlogInterfaces.ILogContext;
|
||||
public minimumLogLevel: plugins.smartlogInterfaces.TLogLevel;
|
||||
|
||||
public uniInstanceId: string = plugins.isounique.uni();
|
||||
|
||||
export class Smartlog {
|
||||
private logContext: ILogContext;
|
||||
private consoleEnabled: boolean;
|
||||
private minimumLevel: TLogLevel;
|
||||
private runtime: TRuntime;
|
||||
|
||||
private logRouter = new LogRouter();
|
||||
|
||||
public addLogDestination(logDestinationArg: plugins.smartlogInterfaces.ILogDestination) {
|
||||
this.logRouter.addLogDestination(logDestinationArg);
|
||||
}
|
||||
|
||||
constructor(optionsArg: ISmartlogContructorOptions) {
|
||||
this.logContext = optionsArg.logContext;
|
||||
this.minimumLogLevel = optionsArg.minimumLogLevel || 'silly';
|
||||
}
|
||||
|
||||
// ============
|
||||
// Logger Setup
|
||||
// ============
|
||||
@@ -15,43 +46,119 @@ export class Smartlog {
|
||||
/**
|
||||
* enables console logging
|
||||
*/
|
||||
enableConsole() {
|
||||
public enableConsole(optionsArg?: { captureAll: boolean }) {
|
||||
if (globalThis.process && optionsArg && optionsArg.captureAll) {
|
||||
const process = globalThis.process;
|
||||
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
||||
const originalStderrWrite = process.stderr.write.bind(process.stderr);
|
||||
|
||||
process.stdout.write = (...args: any) => {
|
||||
const logString: string = args[0];
|
||||
if (!logString || typeof logString !== 'string') {
|
||||
// continue as planned
|
||||
return originalStdoutWrite(...args);
|
||||
}
|
||||
|
||||
if (!logString.startsWith('LOG')) {
|
||||
if (logString.includes('Error:')) {
|
||||
this.log('error', logString);
|
||||
} else {
|
||||
this.log('info', logString);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return originalStdoutWrite(...args);
|
||||
};
|
||||
|
||||
process.stderr.write = (...args: any) => {
|
||||
const logString: string = args[0];
|
||||
if (!logString || typeof logString !== 'string' || !logString.startsWith('LOG')) {
|
||||
this.log('error', logString);
|
||||
return true;
|
||||
}
|
||||
return originalStderrWrite(...args);
|
||||
};
|
||||
}
|
||||
this.consoleEnabled = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* set a minimum serverity level to log
|
||||
* @param levelArg
|
||||
*/
|
||||
level(levelArg: TLogLevel) {}
|
||||
|
||||
// =============
|
||||
// log functions
|
||||
// =============
|
||||
/**
|
||||
* log stuff
|
||||
* @param logLevelArg
|
||||
* @param logMessageArg
|
||||
* main log method
|
||||
* @param logLevelArg - the log level
|
||||
* @param logMessageArg - the log message
|
||||
* @param logDataArg - any additional log data
|
||||
* @param correlationArg - info about corrleations
|
||||
*/
|
||||
log(logLevelArg: TLogLevel, logMessageArg: string) {}
|
||||
public async log(
|
||||
logLevelArg: plugins.smartlogInterfaces.TLogLevel,
|
||||
logMessageArg: string,
|
||||
logDataArg?: any,
|
||||
correlationArg?: plugins.smartlogInterfaces.ILogCorrelation,
|
||||
) {
|
||||
correlationArg = {
|
||||
...{
|
||||
id: plugins.isounique.uni(),
|
||||
type: 'none',
|
||||
instance: this.uniInstanceId,
|
||||
},
|
||||
...correlationArg,
|
||||
};
|
||||
|
||||
silly(logMessageArg: string) {
|
||||
this.log('silly', logMessageArg);
|
||||
if (this.consoleEnabled) {
|
||||
this.safeConsoleLog(`${logLevelArg}: ${logMessageArg}`);
|
||||
}
|
||||
|
||||
const logPackage: plugins.smartlogInterfaces.ILogPackage = {
|
||||
timestamp: Date.now(),
|
||||
type: 'log',
|
||||
context: this.logContext,
|
||||
level: logLevelArg,
|
||||
correlation: correlationArg,
|
||||
message: logMessageArg,
|
||||
};
|
||||
if (logDataArg) {
|
||||
logPackage.data = logDataArg;
|
||||
}
|
||||
await this.logRouter.routeLog(logPackage);
|
||||
}
|
||||
|
||||
debug(logMessageArg) {
|
||||
this.log('debug', logMessageArg);
|
||||
public increment(
|
||||
logLevelArg: plugins.smartlogInterfaces.TLogLevel,
|
||||
logMessageArg: string,
|
||||
logDataArg?: any,
|
||||
correlationArg: plugins.smartlogInterfaces.ILogCorrelation = {
|
||||
id: plugins.isounique.uni(),
|
||||
type: 'none',
|
||||
},
|
||||
) {
|
||||
if (this.consoleEnabled) {
|
||||
this.safeConsoleLog(`INCREMENT: ${logLevelArg}: ${logMessageArg}`);
|
||||
}
|
||||
this.logRouter.routeLog({
|
||||
timestamp: Date.now(),
|
||||
type: 'increment',
|
||||
context: this.logContext,
|
||||
level: logLevelArg,
|
||||
message: logMessageArg,
|
||||
correlation: correlationArg,
|
||||
});
|
||||
}
|
||||
|
||||
info(logMessageArg: string) {
|
||||
this.log('info', logMessageArg);
|
||||
public async handleLog(logPackageArg: plugins.smartlogInterfaces.ILogPackage) {
|
||||
await this.logRouter.routeLog(logPackageArg);
|
||||
}
|
||||
|
||||
warn(logMessageArg) {
|
||||
this.log('warn', logMessageArg);
|
||||
private safeConsoleLog(logLine: string) {
|
||||
console.log(
|
||||
`LOG => ${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()} => ${logLine}`,
|
||||
);
|
||||
}
|
||||
|
||||
error(logMessageArg) {
|
||||
this.log('error', logMessageArg);
|
||||
public createLogGroup(transactionId: string = 'none') {
|
||||
return new LogGroup(this, transactionId);
|
||||
}
|
||||
}
|
||||
|
@@ -1 +1,4 @@
|
||||
export {};
|
||||
import * as isounique from '@push.rocks/isounique';
|
||||
import * as smartlogInterfaces from '../dist_ts_interfaces/index.js';
|
||||
|
||||
export { isounique, smartlogInterfaces };
|
||||
|
3
ts_context/index.ts
Normal file
3
ts_context/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import * as plugins from './smartlog-context.plugins.js';
|
||||
|
||||
export let standardExport = 'Hi there! :) This is an exported string';
|
6
ts_context/smartlog-context.plugins.ts
Normal file
6
ts_context/smartlog-context.plugins.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
// node native scope
|
||||
import * as path from 'path';
|
||||
|
||||
export {
|
||||
path
|
||||
}
|
8
ts_destination_clickhouse/00_commitinfo_data.ts
Normal file
8
ts_destination_clickhouse/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartlog-destination-clickhouse',
|
||||
version: '1.0.14',
|
||||
description: 'A library to integrate Smartlog logging with ClickHouse database for efficient log storage and querying.'
|
||||
}
|
30
ts_destination_clickhouse/index.ts
Normal file
30
ts_destination_clickhouse/index.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import * as plugins from './slclick.plugins.js';
|
||||
|
||||
export class SmartlogDestinationClickhouse implements plugins.smartlogInterfaces.ILogDestination {
|
||||
// STATIC
|
||||
public static async createAndStart(
|
||||
optionsArg: plugins.smartclickhouse.IClickhouseConstructorOptions
|
||||
) {
|
||||
const destinationClickhouse = new SmartlogDestinationClickhouse(optionsArg);
|
||||
await destinationClickhouse.start();
|
||||
return destinationClickhouse;
|
||||
}
|
||||
|
||||
// INSTANCE
|
||||
private smartclickhouseDb: plugins.smartclickhouse.SmartClickHouseDb;
|
||||
private logTable: plugins.smartclickhouse.TimeDataTable;
|
||||
constructor(options: plugins.smartclickhouse.IClickhouseConstructorOptions) {
|
||||
this.smartclickhouseDb = new plugins.smartclickhouse.SmartClickHouseDb(options);
|
||||
}
|
||||
|
||||
public async start() {
|
||||
await this.smartclickhouseDb.start();
|
||||
this.logTable = await this.smartclickhouseDb.getTable('logs');
|
||||
}
|
||||
|
||||
public async handleLog(
|
||||
logPackage: plugins.smartlogInterfaces.ILogPackage<unknown>
|
||||
): Promise<void> {
|
||||
await this.logTable.addData(logPackage);
|
||||
}
|
||||
}
|
5
ts_destination_clickhouse/slclick.plugins.ts
Normal file
5
ts_destination_clickhouse/slclick.plugins.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
// pushrocks scope
|
||||
import * as smartlogInterfaces from '../dist_ts_interfaces/index.js';
|
||||
import * as smartclickhouse from '@push.rocks/smartclickhouse';
|
||||
|
||||
export { smartlogInterfaces, smartclickhouse };
|
8
ts_destination_devtools/00_commitinfo_data.ts
Normal file
8
ts_destination_devtools/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartlog-destination-devtools',
|
||||
version: '1.0.12',
|
||||
description: 'A library enabling enhanced logging in browser development tools.'
|
||||
}
|
58
ts_destination_devtools/index.ts
Normal file
58
ts_destination_devtools/index.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import * as plugins from './plugins.js';
|
||||
import type { ILogDestination, ILogPackage } from '../dist_ts_interfaces/index.js';
|
||||
|
||||
export class SmartlogDestinationDevtools implements ILogDestination {
|
||||
public async handleLog(logPackageArg: ILogPackage) {
|
||||
await this.logInBrowser(logPackageArg);
|
||||
}
|
||||
|
||||
private async logInBrowser(logPackage: ILogPackage) {
|
||||
switch (logPackage.level) {
|
||||
case 'error':
|
||||
console.log(
|
||||
`%c Error: %c ${logPackage.message}`,
|
||||
'background:#000000;color:#800000;',
|
||||
'color:#000000;'
|
||||
);
|
||||
break;
|
||||
case 'info':
|
||||
console.log(
|
||||
`%c Info: %c ${logPackage.message}`,
|
||||
'background:#EC407A;color:#ffffff;',
|
||||
'color:#EC407A;'
|
||||
);
|
||||
break;
|
||||
case 'ok':
|
||||
console.log(
|
||||
`%c OK: %c ${logPackage.message}`,
|
||||
'background:#000000;color:#8BC34A;',
|
||||
'color:#000000;'
|
||||
);
|
||||
break;
|
||||
case 'success':
|
||||
console.log(
|
||||
`%c Success: %c ${logPackage.message}`,
|
||||
'background:#8BC34A;color:#ffffff;',
|
||||
'color:#8BC34A;'
|
||||
);
|
||||
break;
|
||||
case 'warn':
|
||||
console.log(
|
||||
`%c Warn: %c ${logPackage.message}`,
|
||||
'background:#000000;color:#FB8C00;',
|
||||
'color:#000000;'
|
||||
);
|
||||
break;
|
||||
case 'note':
|
||||
console.log(
|
||||
`%c Note: %c ${logPackage.message}`,
|
||||
'background:#42A5F5;color:#ffffff',
|
||||
'color:#42A5F5;'
|
||||
);
|
||||
break;
|
||||
default:
|
||||
console.log(`unknown logType for "${logPackage.message}"`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
2
ts_destination_devtools/plugins.ts
Normal file
2
ts_destination_devtools/plugins.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
import * as smartlogInterfaces from '../dist_ts_interfaces/index.js';
|
||||
export { smartlogInterfaces };
|
23
ts_destination_file/index.ts
Normal file
23
ts_destination_file/index.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import * as plugins from './smartfile-destination-file.plugins.js';
|
||||
|
||||
export class SmartlogDestinationFile implements plugins.smartlogInterfaces.ILogDestination {
|
||||
public fileWriteStream: plugins.fs.WriteStream;
|
||||
|
||||
public async handleLog(logPackageArg: plugins.smartlogInterfaces.ILogPackage) {
|
||||
this.fileWriteStream.write(`${new plugins.smarttime.ExtendedDate(Date.now()).toISOString()}: ${logPackageArg.message} \n`);
|
||||
}
|
||||
|
||||
constructor(filePathArg: string) {
|
||||
const extendedDate = new plugins.smarttime.ExtendedDate(Date.now());
|
||||
if (!plugins.path.isAbsolute(filePathArg)) {
|
||||
throw new Error(`filePath needs to be absolute but is not: "${filePathArg}"`);
|
||||
}
|
||||
plugins.smartfile.fs.ensureFileSync(filePathArg, `# Smartlogfile. Created at ${extendedDate.toISOString()}\n`);
|
||||
this.fileWriteStream = plugins.fs.createWriteStream(
|
||||
filePathArg,
|
||||
{
|
||||
flags: 'a+',
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
19
ts_destination_file/smartfile-destination-file.plugins.ts
Normal file
19
ts_destination_file/smartfile-destination-file.plugins.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
// node native scope
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
export {
|
||||
fs,
|
||||
path
|
||||
};
|
||||
|
||||
// pushrocks scope
|
||||
import * as smartfile from '@push.rocks/smartfile';
|
||||
import * as smartlogInterfaces from '../dist_ts_interfaces/index.js';
|
||||
import * as smarttime from '@push.rocks/smarttime';
|
||||
|
||||
export {
|
||||
smartfile,
|
||||
smartlogInterfaces,
|
||||
smarttime
|
||||
};
|
8
ts_destination_local/00_commitinfo_data.ts
Normal file
8
ts_destination_local/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartlog-destination-local',
|
||||
version: '9.0.2',
|
||||
description: 'a smartlog destination targeting the local console'
|
||||
}
|
142
ts_destination_local/classes.destinationlocal.ts
Normal file
142
ts_destination_local/classes.destinationlocal.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import * as plugins from './plugins.js';
|
||||
import type { ILogDestination, ILogPackage, TLogLevel } from '../dist_ts_interfaces/index.js';
|
||||
|
||||
// other beautylog classes
|
||||
import { type TColorName } from '@push.rocks/consolecolor';
|
||||
|
||||
export class DestinationLocal implements ILogDestination {
|
||||
/**
|
||||
* handles a log according to the smartlog standard
|
||||
* @param logPackage
|
||||
*/
|
||||
public async handleLog(logPackage: ILogPackage) {
|
||||
this.logToConsole(logPackage);
|
||||
}
|
||||
|
||||
/**
|
||||
* creates a new empty line
|
||||
* @param linesArg
|
||||
* @returns void
|
||||
*/
|
||||
public newLine(linesArg: number = 1) {
|
||||
for (let i = 0; i < linesArg; i++) {
|
||||
console.log('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* logs a reduced log that only logs changes of consequential log messages
|
||||
*/
|
||||
public logReduced(logTextArg: string, repeatEveryTimesArg: number = 0) {
|
||||
if (
|
||||
logTextArg === this.previousMessage &&
|
||||
(repeatEveryTimesArg === 0 || this.sameMessageCounter !== repeatEveryTimesArg)
|
||||
) {
|
||||
this.sameMessageCounter++;
|
||||
} else {
|
||||
this.sameMessageCounter = 0;
|
||||
this.previousMessage = logTextArg;
|
||||
this.logToConsole({
|
||||
timestamp: Date.now(),
|
||||
type: 'log',
|
||||
level: 'info',
|
||||
context: {
|
||||
company: 'undefined',
|
||||
companyunit: 'undefined',
|
||||
containerName: 'undefined',
|
||||
environment: 'test',
|
||||
runtime: 'node',
|
||||
zone: 'undefined',
|
||||
},
|
||||
message: logTextArg,
|
||||
correlation: {
|
||||
id: 'none',
|
||||
type: 'none',
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
private previousMessage: string = '';
|
||||
private sameMessageCounter: number = 0;
|
||||
|
||||
// default logging
|
||||
private logToConsole(logPackageArg: ILogPackage) {
|
||||
try {
|
||||
const style = this.localBl[logPackageArg.level] ?? this.localBl.info;
|
||||
const logString =
|
||||
style.prefix +
|
||||
plugins.consolecolor.coloredString(
|
||||
logPackageArg.message,
|
||||
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.error.prefix +
|
||||
'You seem to have tried logging something strange ' +
|
||||
error
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private localBl: {
|
||||
[key: string]: {
|
||||
prefix: string;
|
||||
textColor: TColorName;
|
||||
};
|
||||
} = {
|
||||
silly: {
|
||||
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') +
|
||||
plugins.consolecolor.coloredString(' ERROR! ', 'red', 'black') +
|
||||
' ',
|
||||
textColor: 'red',
|
||||
},
|
||||
info: {
|
||||
prefix:
|
||||
plugins.consolecolor.coloredString(' ', 'blue', 'blue') +
|
||||
plugins.consolecolor.coloredString(' info: ', 'blue', 'black') +
|
||||
' ',
|
||||
textColor: 'white',
|
||||
},
|
||||
note: {
|
||||
prefix:
|
||||
plugins.consolecolor.coloredString(' ', 'pink', 'pink') +
|
||||
plugins.consolecolor.coloredString(' note -> ', 'pink', 'black') +
|
||||
' ',
|
||||
textColor: 'pink',
|
||||
},
|
||||
ok: {
|
||||
prefix:
|
||||
plugins.consolecolor.coloredString(' ', 'green', 'green') +
|
||||
plugins.consolecolor.coloredString(' ok ', 'green', 'black') +
|
||||
' ',
|
||||
textColor: 'green',
|
||||
},
|
||||
success: {
|
||||
prefix:
|
||||
plugins.consolecolor.coloredString(' ', 'green', 'green') +
|
||||
plugins.consolecolor.coloredString(' SUCCESS! ', 'green', 'black') +
|
||||
' ',
|
||||
textColor: 'green',
|
||||
},
|
||||
warn: {
|
||||
prefix:
|
||||
plugins.consolecolor.coloredString(' ', 'orange', 'orange') +
|
||||
plugins.consolecolor.coloredString(' WARN -> ', 'orange', 'black') +
|
||||
' ',
|
||||
textColor: 'orange',
|
||||
},
|
||||
};
|
||||
}
|
2
ts_destination_local/index.ts
Normal file
2
ts_destination_local/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
// export classes
|
||||
export { DestinationLocal } from './classes.destinationlocal.js';
|
5
ts_destination_local/plugins.ts
Normal file
5
ts_destination_local/plugins.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import * as consolecolor from '@push.rocks/consolecolor';
|
||||
import * as smartlogInterfaces from '../dist_ts_interfaces/index.js';
|
||||
import * as smartpromise from '@push.rocks/smartpromise';
|
||||
|
||||
export { consolecolor, smartlogInterfaces, smartpromise };
|
8
ts_destination_receiver/00_commitinfo_data.ts
Normal file
8
ts_destination_receiver/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartlog-destination-receiver',
|
||||
version: '2.0.6',
|
||||
description: 'A package providing a destination handler for smartlog logging packages'
|
||||
}
|
35
ts_destination_receiver/index.ts
Normal file
35
ts_destination_receiver/index.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import * as plugins from './smartlog-destination-receiver.plugins.js';
|
||||
import {
|
||||
type ILogDestination,
|
||||
type ILogPackageAuthenticated,
|
||||
type ILogPackage,
|
||||
} from '../dist_ts_interfaces/index.js';
|
||||
|
||||
export interface ISmartlogDestinationReceiverConstructorOptions {
|
||||
passphrase: string;
|
||||
receiverEndpoint: string;
|
||||
}
|
||||
|
||||
export class SmartlogDestinationReceiver implements ILogDestination {
|
||||
private options: ISmartlogDestinationReceiverConstructorOptions;
|
||||
private webrequest = new plugins.webrequest.WebRequest();
|
||||
|
||||
constructor(optionsArg: ISmartlogDestinationReceiverConstructorOptions) {
|
||||
this.options = optionsArg;
|
||||
}
|
||||
|
||||
private errorCounter = 0;
|
||||
public async handleLog(logPackageArg: ILogPackage) {
|
||||
const response = await this.webrequest.postJson(this.options.receiverEndpoint, {
|
||||
auth: plugins.smarthash.sha256FromStringSync(this.options.passphrase),
|
||||
logPackage: logPackageArg,
|
||||
}).catch(err => {
|
||||
if (this.errorCounter % 100 === 0) {
|
||||
console.error(`There seems to be an error with logging.`);
|
||||
console.error(`Accumulated ${this.errorCounter} errors so far`)
|
||||
}
|
||||
this.errorCounter++;
|
||||
});
|
||||
return response.body;
|
||||
}
|
||||
}
|
@@ -0,0 +1,5 @@
|
||||
import * as smarthash from '@push.rocks/smarthash';
|
||||
import * as smartlogInterfaces from '../dist_ts_interfaces/index.js';
|
||||
import * as webrequest from '@push.rocks/webrequest';
|
||||
|
||||
export { smarthash, smartlogInterfaces, webrequest };
|
8
ts_interfaces/00_commitinfo_data.ts
Normal file
8
ts_interfaces/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartlog-interfaces',
|
||||
version: '3.0.2',
|
||||
description: 'Defines interfaces for the smartlog ecosystem.'
|
||||
}
|
126
ts_interfaces/index.ts
Normal file
126
ts_interfaces/index.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import * as plugins from './smartlog-interfaces.plugins.js';
|
||||
|
||||
import * as requestInterfaces from './smartlog-interfaces.requests.js';
|
||||
|
||||
export { requestInterfaces as request };
|
||||
|
||||
/**
|
||||
* the different available log types
|
||||
*/
|
||||
export type TLogType =
|
||||
| 'log'
|
||||
| 'increment'
|
||||
| 'gauge'
|
||||
| 'error'
|
||||
| 'success'
|
||||
| 'value'
|
||||
| 'finance'
|
||||
| 'compliance';
|
||||
|
||||
/**
|
||||
* the available log levels
|
||||
*/
|
||||
export type TLogLevel =
|
||||
| 'silly'
|
||||
| 'info'
|
||||
| 'debug'
|
||||
| 'note'
|
||||
| 'ok'
|
||||
| 'success'
|
||||
| 'warn'
|
||||
| 'error'
|
||||
| 'lifecycle';
|
||||
|
||||
/**
|
||||
* the available environments
|
||||
*/
|
||||
export type TEnvironment = 'local' | 'test' | 'staging' | 'production';
|
||||
|
||||
/**
|
||||
* the available runtimes
|
||||
*/
|
||||
export type TRuntime = 'node' | 'chrome' | 'rust' | 'deno' | 'cloudflare_workers';
|
||||
|
||||
/**
|
||||
* the log context e.g. what app in what version on what server
|
||||
*/
|
||||
export interface ILogContext {
|
||||
commitinfo?: plugins.tsclass.code.ICommitInfo;
|
||||
company?: string;
|
||||
companyunit?: string;
|
||||
containerName?: string;
|
||||
environment?: TEnvironment;
|
||||
runtime?: TRuntime;
|
||||
zone?: string;
|
||||
}
|
||||
|
||||
export interface ILogCorrelation {
|
||||
/**
|
||||
* a unique id for this log
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* the type of this log
|
||||
*/
|
||||
type: 'none' | 'service' | 'build' | 'infrastructure' | 'cdn';
|
||||
/**
|
||||
* the instance on which the log is created
|
||||
* use it for pinning logs to a certain instance in a cluster
|
||||
*/
|
||||
instance?: string;
|
||||
/**
|
||||
* a series of logs
|
||||
*/
|
||||
group?: string;
|
||||
/**
|
||||
* a log that belongs to a transaction. E.g. a Payment or a request traveling through multiple backend instances
|
||||
*/
|
||||
transaction?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* the main logpackage
|
||||
*/
|
||||
export interface ILogPackage<T = unknown> {
|
||||
/**
|
||||
* a unix timestamp in milliseconds
|
||||
*/
|
||||
timestamp: number;
|
||||
type: TLogType;
|
||||
context: ILogContext;
|
||||
level: TLogLevel;
|
||||
/**
|
||||
* allows grouping of log messages
|
||||
*/
|
||||
correlation: ILogCorrelation;
|
||||
/**
|
||||
* the message to log
|
||||
*/
|
||||
message: string;
|
||||
data?: T;
|
||||
}
|
||||
|
||||
export interface ILogPackageDataRequest {
|
||||
requestCorrelationId: string;
|
||||
url: string;
|
||||
pathname: string;
|
||||
method: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface ILogPackageAuthenticated {
|
||||
auth: string;
|
||||
logPackage: ILogPackage;
|
||||
}
|
||||
|
||||
export interface ILogPackageArrayAuthenticated {
|
||||
auth: string;
|
||||
logPackages: ILogPackage[];
|
||||
}
|
||||
|
||||
/**
|
||||
* a destination interface for extending smartlog modules
|
||||
*/
|
||||
export interface ILogDestination {
|
||||
handleLog: (logPackage: ILogPackage) => Promise<void>;
|
||||
}
|
10
ts_interfaces/smartlog-interfaces.plugins.ts
Normal file
10
ts_interfaces/smartlog-interfaces.plugins.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
|
||||
|
||||
export { typedrequestInterfaces };
|
||||
|
||||
// tsclass scope
|
||||
import * as tsclass from '@tsclass/tsclass';
|
||||
|
||||
export {
|
||||
tsclass
|
||||
}
|
9
ts_interfaces/smartlog-interfaces.requests.ts
Normal file
9
ts_interfaces/smartlog-interfaces.requests.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { type ILogPackageAuthenticated } from './index.js';
|
||||
|
||||
export interface IRequest_SmartlogDestinationReceiver_Any_PostLogPackages {
|
||||
method: 'postLogPackages';
|
||||
request: {
|
||||
logPackages: ILogPackageAuthenticated[];
|
||||
};
|
||||
response: {};
|
||||
}
|
8
ts_receiver/00_commitinfo_data.ts
Normal file
8
ts_receiver/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartlog-receiver',
|
||||
version: '2.0.0',
|
||||
description: 'a receiver for smartlog-destination-receiver'
|
||||
}
|
1
ts_receiver/index.ts
Normal file
1
ts_receiver/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './sl.classes.smartlogreceiver.js';
|
73
ts_receiver/sl.classes.smartlogreceiver.ts
Normal file
73
ts_receiver/sl.classes.smartlogreceiver.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import * as plugins from './sl.receiver.plugins.js';
|
||||
|
||||
import type {
|
||||
ILogPackage,
|
||||
ILogPackageAuthenticated,
|
||||
ILogDestination,
|
||||
} from '../dist_ts_interfaces/index.js';
|
||||
|
||||
export type TValidatorFunction = (logPackage: ILogPackage) => Promise<boolean>;
|
||||
|
||||
export interface ISmartlogReceiverOptions {
|
||||
smartlogInstance: plugins.smartlog.Smartlog;
|
||||
passphrase: string;
|
||||
validatorFunction: TValidatorFunction;
|
||||
}
|
||||
|
||||
/**
|
||||
* a class that receives smartlog packages
|
||||
*/
|
||||
export class SmartlogReceiver {
|
||||
public passphrase: string;
|
||||
public validatorFunction: TValidatorFunction;
|
||||
public smartlogInstance: plugins.smartlog.Smartlog;
|
||||
|
||||
constructor(smartlogReceiverOptions: ISmartlogReceiverOptions) {
|
||||
this.passphrase = smartlogReceiverOptions.passphrase;
|
||||
this.validatorFunction =
|
||||
smartlogReceiverOptions.validatorFunction ||
|
||||
(async (logpackageArg) => {
|
||||
return true;
|
||||
});
|
||||
this.smartlogInstance = smartlogReceiverOptions.smartlogInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* handles a authenticated log
|
||||
*/
|
||||
public async handleAuthenticatedLog(authenticatedLogPackageArg: ILogPackageAuthenticated) {
|
||||
const authString = authenticatedLogPackageArg.auth;
|
||||
const logPackage = authenticatedLogPackageArg.logPackage;
|
||||
|
||||
if (
|
||||
authString === plugins.smarthash.sha256FromStringSync(this.passphrase) &&
|
||||
(await this.validatorFunction(logPackage))
|
||||
) {
|
||||
// Message authenticated lets clean up.
|
||||
logPackage.correlation ? null : (logPackage.correlation = { id: '123', type: 'none' });
|
||||
logPackage.correlation.id ? null : (logPackage.correlation.id = '123');
|
||||
logPackage.correlation.type ? null : (logPackage.correlation.type = 'none');
|
||||
|
||||
this.smartlogInstance.handleLog(logPackage);
|
||||
return { status: 'ok' };
|
||||
} else {
|
||||
this.smartlogInstance.log('error', 'Message rejected because of bad passphrase');
|
||||
return { status: 'error' };
|
||||
// console.log(plugins.smarthash.sha256FromStringSync(this.passphrase));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* handles an array of authenticated logs
|
||||
* @param authenticatedLogsPackageArrayArg
|
||||
*/
|
||||
public async handleManyAuthenticatedLogs(
|
||||
authenticatedLogsPackageArrayArg: ILogPackageAuthenticated[]
|
||||
) {
|
||||
const promiseArray: Array<Promise<any>> = [];
|
||||
for (const logPackage of authenticatedLogsPackageArrayArg) {
|
||||
promiseArray.push(this.handleAuthenticatedLog(logPackage));
|
||||
}
|
||||
await Promise.all(promiseArray);
|
||||
}
|
||||
}
|
4
ts_receiver/sl.receiver.plugins.ts
Normal file
4
ts_receiver/sl.receiver.plugins.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import * as smarthash from '@push.rocks/smarthash';
|
||||
import * as smartlog from '../dist_ts/index.js';
|
||||
|
||||
export { smartlog, smarthash };
|
417
ts_source_interactive/index.ts
Normal file
417
ts_source_interactive/index.ts
Normal 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
|
||||
}
|
||||
}
|
10
ts_source_interactive/smartlog-source-interactive.plugins.ts
Normal file
10
ts_source_interactive/smartlog-source-interactive.plugins.ts
Normal 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 };
|
16
tsconfig.json
Normal file
16
tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {}
|
||||
},
|
||||
"exclude": [
|
||||
"dist_*/**/*.d.ts"
|
||||
]
|
||||
}
|
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"extends": "tslint-config-standard"
|
||||
}
|
Reference in New Issue
Block a user