Compare commits
17 Commits
Author | SHA1 | Date | |
---|---|---|---|
3d0fc6adc5 | |||
d16e3b613c | |||
af18c2f57a | |||
9476ad8129 | |||
d1284024d5 | |||
0114de2690 | |||
011f8427c1 | |||
3866cb9580 | |||
31140af566 | |||
c4b9833145 | |||
3c6d217563 | |||
8524299d39 | |||
227931b0d3 | |||
e3be31bb93 | |||
3babab347f | |||
765b388889 | |||
80b0bdd663 |
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
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -3,7 +3,6 @@
|
||||
# artifacts
|
||||
coverage/
|
||||
public/
|
||||
pages/
|
||||
|
||||
# installs
|
||||
node_modules/
|
||||
@ -17,4 +16,4 @@ node_modules/
|
||||
dist/
|
||||
dist_*/
|
||||
|
||||
# custom
|
||||
#------# custom
|
127
.gitlab-ci.yml
127
.gitlab-ci.yml
@ -1,127 +0,0 @@
|
||||
# gitzone ci_default
|
||||
image: registry.gitlab.com/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:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
audit:
|
||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
||||
stage: security
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci command npm install --ignore-scripts
|
||||
- npmci command npm config set registry https://registry.npmjs.org
|
||||
- npmci command npm audit --audit-level=high
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
# ====================
|
||||
# test stage
|
||||
# ====================
|
||||
|
||||
testStable:
|
||||
stage: test
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci npm test
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- priv
|
||||
|
||||
testBuild:
|
||||
stage: test
|
||||
script:
|
||||
- npmci npm prepare
|
||||
- npmci node install stable
|
||||
- npmci npm install
|
||||
- npmci command npm run build
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
release:
|
||||
stage: release
|
||||
script:
|
||||
- npmci node install stable
|
||||
- npmci npm publish
|
||||
only:
|
||||
- tags
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
# ====================
|
||||
# metadata stage
|
||||
# ====================
|
||||
codequality:
|
||||
stage: metadata
|
||||
allow_failure: true
|
||||
script:
|
||||
- npmci command npm install -g tslint typescript
|
||||
- npmci npm prepare
|
||||
- npmci npm install
|
||||
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- priv
|
||||
|
||||
trigger:
|
||||
stage: metadata
|
||||
script:
|
||||
- npmci trigger
|
||||
only:
|
||||
- tags
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
|
||||
pages:
|
||||
stage: metadata
|
||||
script:
|
||||
- npmci node install lts
|
||||
- npmci command npm install -g @gitzone/tsdoc
|
||||
- npmci npm prepare
|
||||
- npmci npm install
|
||||
- npmci command tsdoc
|
||||
tags:
|
||||
- lossless
|
||||
- docker
|
||||
- notpriv
|
||||
only:
|
||||
- tags
|
||||
artifacts:
|
||||
expire_in: 1 week
|
||||
paths:
|
||||
- public
|
||||
allow_failure: true
|
24
.vscode/launch.json
vendored
24
.vscode/launch.json
vendored
@ -2,28 +2,10 @@
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "current file",
|
||||
"type": "node",
|
||||
"command": "npm test",
|
||||
"name": "Run npm test",
|
||||
"request": "launch",
|
||||
"args": [
|
||||
"${relativeFile}"
|
||||
],
|
||||
"runtimeArgs": ["-r", "@gitzone/tsrun"],
|
||||
"cwd": "${workspaceRoot}",
|
||||
"protocol": "inspector",
|
||||
"internalConsoleOptions": "openOnSessionStart"
|
||||
},
|
||||
{
|
||||
"name": "test.ts",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"args": [
|
||||
"test/test.ts"
|
||||
],
|
||||
"runtimeArgs": ["-r", "@gitzone/tsrun"],
|
||||
"cwd": "${workspaceRoot}",
|
||||
"protocol": "inspector",
|
||||
"internalConsoleOptions": "openOnSessionStart"
|
||||
"type": "node-terminal"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@ -15,7 +15,7 @@
|
||||
"properties": {
|
||||
"projectType": {
|
||||
"type": "string",
|
||||
"enum": ["website", "element", "service", "npm"]
|
||||
"enum": ["website", "element", "service", "npm", "wcc"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
57
changelog.md
Normal file
57
changelog.md
Normal file
@ -0,0 +1,57 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-01-18 - 2.1.0 - feat(ci)
|
||||
Add GitHub Actions workflows for CI/CD
|
||||
|
||||
- Introduce GitHub Actions workflows to handle CI/CD processes for different events and branch types.
|
||||
- Remove GitLab CI configuration in favor of GitHub Actions.
|
||||
- Ensure security audits and tests are run as part of the CI pipeline.
|
||||
|
||||
## 2024-05-29 to 2024-03-30 - 2.0.0 - Configuration Updates
|
||||
Improvements and updates to configuration files.
|
||||
|
||||
- Updated project description
|
||||
- Modified TypeScript configuration
|
||||
- Updated npmextra.json for githost details
|
||||
|
||||
## 2023-07-11 to 2023-07-10 - 2.0.0 - Organizational Change
|
||||
Transitioned to a new organizational scheme for improved project structure.
|
||||
|
||||
- Implemented new organizational scheme
|
||||
|
||||
## 2023-01-12 - 1.0.29 - Breaking Change
|
||||
Important breaking changes introduced, switched project to ECMAScript Module (ESM) format.
|
||||
|
||||
- Switched to ECMAScript Module (ESM)
|
||||
- Core functionality updated
|
||||
|
||||
## 2021-09-17 to 2020-07-20 - 1.0.28 to 1.0.23 - Core Fixes
|
||||
Multiple core improvements and bug fixes across several versions.
|
||||
|
||||
- Core functionality updates across versions
|
||||
|
||||
## 2018-03-09 to 2018-03-05 - 1.0.21 to 1.0.20 - Documentation Updates
|
||||
Enhancements and updates to project documentation.
|
||||
|
||||
- License information updated in README
|
||||
- General README updates
|
||||
|
||||
## 2018-03-05 - 1.0.19 - Standards Update
|
||||
Updated project to comply with the latest coding standards.
|
||||
|
||||
- Applied latest standard updates
|
||||
|
||||
## 2018-03-03 - 1.0.18 - Initial Working Version
|
||||
Initial release with all dependencies configured.
|
||||
|
||||
- First working project version with dependencies
|
||||
|
||||
## 2017-10-16 - 1.0.2 - Documentation
|
||||
Initial project documentation added.
|
||||
|
||||
- Added initial README file
|
||||
|
||||
## 2017-10-16 - 1.0.1 - Initial Release
|
||||
The initial release of the project.
|
||||
|
||||
- Project setup and initial commit
|
@ -2,16 +2,30 @@
|
||||
"gitzone": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "gitlab.com",
|
||||
"gitscope": "pushrocks",
|
||||
"githost": "code.foss.global",
|
||||
"gitscope": "push.rocks",
|
||||
"gitrepo": "logcontext",
|
||||
"shortDescription": "enrich logs with context",
|
||||
"npmPackagename": "@pushrocks/logcontext",
|
||||
"license": "MIT"
|
||||
"description": "A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.",
|
||||
"npmPackagename": "@push.rocks/logcontext",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"logging",
|
||||
"context management",
|
||||
"context enrichment",
|
||||
"asynchronous",
|
||||
"scope management",
|
||||
"typescript",
|
||||
"nodejs",
|
||||
"module",
|
||||
"async log contexts"
|
||||
]
|
||||
}
|
||||
},
|
||||
"npmci": {
|
||||
"npmAccessLevel": "public",
|
||||
"npmGlobalTools": []
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
10932
package-lock.json
generated
10932
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
60
package.json
60
package.json
@ -1,30 +1,33 @@
|
||||
{
|
||||
"name": "@pushrocks/logcontext",
|
||||
"version": "1.0.26",
|
||||
"description": "enrich logs with context",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"name": "@push.rocks/smartcontext",
|
||||
"version": "2.1.0",
|
||||
"description": "A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.",
|
||||
"exports": {
|
||||
".": "./dist_ts/index.js"
|
||||
},
|
||||
"type": "module",
|
||||
"author": "Lossless GmbH",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "(tstest test/)",
|
||||
"build": "(tsbuild --web)"
|
||||
"build": "(tsbuild --web)",
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@gitzone/tsbuild": "^2.1.24",
|
||||
"@gitzone/tsbundle": "^1.0.72",
|
||||
"@gitzone/tstest": "^1.0.43",
|
||||
"@pushrocks/smartdelay": "^2.0.10",
|
||||
"@pushrocks/tapbundle": "^3.2.9",
|
||||
"@types/node": "^14.0.23",
|
||||
"tslint": "^6.1.2",
|
||||
"tslint-config-prettier": "^1.18.0"
|
||||
"@git.zone/tsbuild": "^2.1.27",
|
||||
"@git.zone/tsbundle": "^2.0.7",
|
||||
"@git.zone/tsrun": "^1.2.39",
|
||||
"@git.zone/tstest": "^1.0.57",
|
||||
"@push.rocks/smartdelay": "^3.0.5",
|
||||
"@push.rocks/tapbundle": "^5.0.4",
|
||||
"@types/node": "^18.11.18"
|
||||
},
|
||||
"dependencies": {
|
||||
"@pushrocks/lik": "^4.0.17",
|
||||
"@pushrocks/smartcls": "^1.0.9",
|
||||
"@pushrocks/smartunique": "^3.0.3",
|
||||
"@types/shortid": "0.0.29"
|
||||
"@push.rocks/lik": "^6.0.0",
|
||||
"@push.rocks/smartcls": "^1.0.9",
|
||||
"@push.rocks/smartunique": "^3.0.3",
|
||||
"@types/shortid": "0.0.29",
|
||||
"simple-async-context": "^0.0.13"
|
||||
},
|
||||
"private": false,
|
||||
"browserslist": [
|
||||
@ -41,5 +44,24 @@
|
||||
"cli.js",
|
||||
"npmextra.json",
|
||||
"readme.md"
|
||||
]
|
||||
],
|
||||
"keywords": [
|
||||
"logging",
|
||||
"context management",
|
||||
"context enrichment",
|
||||
"asynchronous",
|
||||
"scope management",
|
||||
"typescript",
|
||||
"nodejs",
|
||||
"module",
|
||||
"async log contexts"
|
||||
],
|
||||
"homepage": "https://code.foss.global/push.rocks/logcontext#readme",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://code.foss.global/push.rocks/logcontext.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://code.foss.global/push.rocks/logcontext/issues"
|
||||
}
|
||||
}
|
||||
|
9682
pnpm-lock.yaml
generated
Normal file
9682
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
1
readme.hints.md
Normal file
1
readme.hints.md
Normal file
@ -0,0 +1 @@
|
||||
|
288
readme.md
288
readme.md
@ -1,84 +1,252 @@
|
||||
# @pushrocks/logcontext
|
||||
enrich logs with context
|
||||
# @push.rocks/smartcontext
|
||||
|
||||
## Availabililty and Links
|
||||
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/logcontext)
|
||||
* [gitlab.com (source)](https://gitlab.com/pushrocks/logcontext)
|
||||
* [github.com (source mirror)](https://github.com/pushrocks/logcontext)
|
||||
* [docs (typedoc)](https://pushrocks.gitlab.io/logcontext/)
|
||||
A module to enrich logs with context, featuring async log contexts and scope management.
|
||||
|
||||
## Status for master
|
||||
## Install
|
||||
|
||||
Status Category | Status Badge
|
||||
-- | --
|
||||
GitLab Pipelines | [](https://lossless.cloud)
|
||||
GitLab Pipline Test Coverage | [](https://lossless.cloud)
|
||||
npm | [](https://lossless.cloud)
|
||||
Snyk | [](https://lossless.cloud)
|
||||
TypeScript Support | [](https://lossless.cloud)
|
||||
node Support | [](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
||||
Code Style | [](https://lossless.cloud)
|
||||
PackagePhobia (total standalone install weight) | [](https://lossless.cloud)
|
||||
PackagePhobia (package size on registry) | [](https://lossless.cloud)
|
||||
BundlePhobia (total size when bundled) | [](https://lossless.cloud)
|
||||
Platform support | [](https://lossless.cloud) [](https://lossless.cloud)
|
||||
To install the `@push.rocks/smartcontext` module, you can use npm. Make sure you have Node.js and npm installed on your system. Navigate to your project directory and run the following command:
|
||||
|
||||
```bash
|
||||
npm install @push.rocks/smartcontext
|
||||
```
|
||||
|
||||
This command will download and install the module and its dependencies into your project's `node_modules` directory.
|
||||
|
||||
## Usage
|
||||
|
||||
Use TypeScript for best in class instellisense.
|
||||
The `@push.rocks/smartcontext` module provides an efficient way to enrich your logging with contextual information. It features asynchronous log contexts and scope management, especially useful in complex asynchronous workflows in Node.js applications. This documentation will guide you through its core components: `AsyncContext` and `AsyncStore`.
|
||||
|
||||
the logconext module exposes an easy to use syntax for nodejs style async logcontexts.
|
||||
### Setting Up and Basic Usage
|
||||
|
||||
First, import the necessary classes from the module in your TypeScript application:
|
||||
|
||||
```typescript
|
||||
let testLogger = new logcontext.Logger('testNamespace');
|
||||
import { AsyncContext, AsyncStore } from '@push.rocks/smartcontext';
|
||||
```
|
||||
|
||||
testLogger.scope(async () => {
|
||||
testLogger.addData('id1', {
|
||||
someData: 'someValue',
|
||||
#### Creating a Context
|
||||
|
||||
You can create an `AsyncContext` for managing scope-based data sharing. Each context maintains a top-level `AsyncStore` instance. Let’s create a simple context and store some data:
|
||||
|
||||
```typescript
|
||||
const mainContext = new AsyncContext();
|
||||
|
||||
// Add some data to the store
|
||||
mainContext.store.add('username', 'john_doe');
|
||||
mainContext.store.add('role', 'admin');
|
||||
|
||||
console.log(mainContext.store.get('username')); // Outputs: 'john_doe'
|
||||
console.log(mainContext.store.get('role')); // Outputs: 'admin'
|
||||
```
|
||||
|
||||
This `mainContext` acts as a container for contextual data throughout the lifecycle of your application or a specific code block.
|
||||
|
||||
### Scoping with `runScoped`
|
||||
|
||||
The `runScoped` method allows you to run a function within a specific child `AsyncStore` scope. This is vital for isolating child data during asynchronous operations, while still having access to any relevant parent data:
|
||||
|
||||
```typescript
|
||||
await mainContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('transactionId', 'txn_123456');
|
||||
|
||||
console.log(childStore.get('transactionId')); // Outputs: 'txn_123456'
|
||||
// Child store can also access data from the parent context:
|
||||
console.log(childStore.get('username')); // Outputs: 'john_doe'
|
||||
console.log(childStore.get('role')); // Outputs: 'admin'
|
||||
});
|
||||
```
|
||||
|
||||
Changes made within this child store do not leak back to the parent unless explicitly intended.
|
||||
|
||||
#### Isolating Data in Scoped Functions
|
||||
|
||||
Data added within a child scope is only stored locally, unless you decide to propagate it to the parent. Additionally, you can delete data in the child without affecting the parent:
|
||||
|
||||
```typescript
|
||||
await mainContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('temporaryData', 'tempValue');
|
||||
console.log(childStore.get('temporaryData')); // Outputs: 'tempValue'
|
||||
|
||||
// Delete data in child scope
|
||||
childStore.delete('temporaryData');
|
||||
console.log(childStore.get('temporaryData')); // Outputs: undefined
|
||||
});
|
||||
```
|
||||
|
||||
In this example, `temporaryData` is never propagated to the parent. Once deleted within the scope, it’s gone for that child context.
|
||||
|
||||
### Advanced Usage
|
||||
|
||||
Below are some patterns to demonstrate more advanced scenarios.
|
||||
|
||||
#### Handling Complex Asynchronous Flows
|
||||
|
||||
Consider a scenario where you process a list of user requests asynchronously, assigning each request its own temporary data:
|
||||
|
||||
```typescript
|
||||
import { AsyncContext } from '@push.rocks/smartcontext';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
async function processUserRequests(users: string[], asyncContext: AsyncContext) {
|
||||
for (const user of users) {
|
||||
await asyncContext.runScoped(async (childStore: AsyncStore) => {
|
||||
// Assign a unique request ID
|
||||
const requestId = uuidv4();
|
||||
childStore.add('currentUser', user);
|
||||
childStore.add('requestId', requestId);
|
||||
|
||||
console.log(`Processing user: ${childStore.get('currentUser')} with Request ID: ${childStore.get('requestId')}`);
|
||||
|
||||
// Simulate an async operation
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
console.log(`Completed processing for user: ${childStore.get('currentUser')}`);
|
||||
});
|
||||
testLogger.log('hi');
|
||||
testLogger.error(new Error('custom error message'));
|
||||
setTimeout(() => {
|
||||
outsideFunction(); // log scope will travel through callbacks and promises
|
||||
}, 2000);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let outsideFunction = () => {
|
||||
// Note:
|
||||
// the below testLogger reference will have different contexts
|
||||
// depending from which scope "outsideFunction" was called".
|
||||
testLogger.log('some message');
|
||||
};
|
||||
const mainContext = new AsyncContext();
|
||||
processUserRequests(['alice', 'bob'], mainContext);
|
||||
```
|
||||
|
||||
## class Logger
|
||||
Each user’s scope remains neatly contained while still sharing any parent data (if present). This is highly beneficial in servers that handle multiple requests or tasks in parallel.
|
||||
|
||||
#### Sharing Data Across Scopes
|
||||
|
||||
Occasionally, you may want the child scope to add or modify data that persists in the parent. By default, `childStore` only extends the parent for lookup; changes remain local to the child. If you need truly shared data, you can write data directly to the parent store as well:
|
||||
|
||||
```typescript
|
||||
import { Logger } from 'logcontext';
|
||||
const newContext = new AsyncContext();
|
||||
await newContext.runScoped(async (childStore: AsyncStore) => {
|
||||
// This affects only the child store
|
||||
childStore.add('childMessage', 'I am a child.');
|
||||
|
||||
// instantiate new Logger
|
||||
// argument optional, if left empty auto generated shortid will be used
|
||||
let myLogger = new Logger('myNamespace');
|
||||
|
||||
// create a scope
|
||||
myLogger.scope(async () => {
|
||||
// everything that is appended to the call stack from inside here will have all appended context data available
|
||||
|
||||
// add some scoped context information
|
||||
myLogger.addData('customerId', '12345678');
|
||||
|
||||
// will log something with priviously appended context of this scope in place
|
||||
myLoger.log('awesomeText');
|
||||
// Directly manipulate the parent store if needed:
|
||||
newContext.store.add('parentMessage', 'I am the parent (updated).');
|
||||
});
|
||||
|
||||
// Checking the parent store:
|
||||
console.log(newContext.store.get('parentMessage')); // Outputs: 'I am the parent (updated)'
|
||||
console.log(newContext.store.get('childMessage')); // Outputs: undefined (child-only)
|
||||
```
|
||||
|
||||
## Contribution
|
||||
This approach helps you maintain clarity on what data belongs to the parent vs. a transient child operation.
|
||||
|
||||
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
|
||||
#### Parallel Scopes
|
||||
|
||||
For further information read the linked docs at the top of this readme.
|
||||
When dealing with parallel asynchronous operations, each scope can be maintained independently. For instance, multiple login operations can be handled by the same parent context yet remain separate at runtime:
|
||||
|
||||
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
|
||||
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
|
||||
```typescript
|
||||
import { AsyncContext } from '@push.rocks/smartcontext';
|
||||
|
||||
[](https://maintainedby.lossless.com)
|
||||
const userContext = new AsyncContext();
|
||||
userContext.store.add('appVersion', '1.2.0');
|
||||
|
||||
async function handleUserLogin(userId: string, context: AsyncContext) {
|
||||
await context.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('sessionUser', userId);
|
||||
|
||||
console.log(`User: ${childStore.get('sessionUser')}, App: ${childStore.get('appVersion')}`);
|
||||
// More processing for the user...
|
||||
});
|
||||
}
|
||||
|
||||
await Promise.all([
|
||||
handleUserLogin('user123', userContext),
|
||||
handleUserLogin('user456', userContext),
|
||||
]);
|
||||
```
|
||||
|
||||
In this example, the `userContext` store data (like `appVersion`) is accessible within each child scope, but each user session remains isolated. The parent’s data is shared and read-only for the children, unless children write specifically to the parent context.
|
||||
|
||||
#### Error Handling and Context-Enriched Logging
|
||||
|
||||
By leveraging contextual data, your logs can capture additional diagnostic details automatically:
|
||||
|
||||
```typescript
|
||||
async function performTaskWithLogging(taskId: string, context: AsyncContext) {
|
||||
try {
|
||||
await context.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('taskId', taskId);
|
||||
// Simulate some failing operation
|
||||
throw new Error('Task failed due to unexpected error');
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`[Error] Task ID: ${context.store.get('taskId')}, Error: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const loggingContext = new AsyncContext();
|
||||
performTaskWithLogging('task_789', loggingContext);
|
||||
```
|
||||
|
||||
In the example above, we track `taskId` in the context store, ensuring that any error logs or additional logging statements automatically include that identifying information.
|
||||
|
||||
### Managing Contexts Across Modules
|
||||
|
||||
In large applications, you might want different modules to read or update shared context data without tight coupling between modules. One pattern is to define an `AsyncContext` in a root or shared location and pass it as needed:
|
||||
|
||||
```typescript
|
||||
// main.ts
|
||||
import { AsyncContext } from '@push.rocks/smartcontext';
|
||||
import { userModule } from './userModule';
|
||||
import { billingModule } from './billingModule';
|
||||
|
||||
const globalContext = new AsyncContext();
|
||||
globalContext.store.add('appName', 'SmartContextApp');
|
||||
|
||||
userModule(globalContext);
|
||||
billingModule(globalContext);
|
||||
```
|
||||
|
||||
Then, each module file can utilize that shared context:
|
||||
|
||||
```typescript
|
||||
// userModule.ts
|
||||
export async function userModule(context: AsyncContext) {
|
||||
await context.runScoped(async (childStore) => {
|
||||
childStore.add('moduleName', 'UserModule');
|
||||
console.log(`[UserModule] appName: ${childStore.get('appName')}`);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// billingModule.ts
|
||||
export async function billingModule(context: AsyncContext) {
|
||||
await context.runScoped(async (childStore) => {
|
||||
childStore.add('moduleName', 'BillingModule');
|
||||
console.log(`[BillingModule] appName: ${childStore.get('appName')}`);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
This approach keeps the code cleaner and ensures each module has access to shared data while retaining isolation where needed.
|
||||
|
||||
`@push.rocks/smartcontext` equips developers with a sophisticated asynchronous context management system, helping maintain clarity and consistency in logging and context sharing. Here’s a recap of the benefits:
|
||||
|
||||
- **Scoped Data**: Run logical operations within isolated child scopes, reducing contamination of global or parent-level data.
|
||||
- **Asynchronous Safety**: Each asynchronous operation can track its own context, preventing race conditions on shared state.
|
||||
- **Enhanced Logging**: Include relevant contextual data in your logs automatically for easier debugging and tracing.
|
||||
- **Module-Friendly**: Share contexts without introducing deep module interdependencies.
|
||||
|
||||
These features simplify building robust Node.js applications, where concurrency and context tracking can otherwise become unwieldy. Enjoy exploring the breadth of this module’s functionality, and tailor it to meet your project’s unique challenges.
|
||||
|
||||
## 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
test/test.ts
101
test/test.ts
@ -1,41 +1,88 @@
|
||||
import { expect, tap } from '@pushrocks/tapbundle';
|
||||
import * as logcontext from '../ts/index';
|
||||
import { tap, expect } from '@push.rocks/tapbundle';
|
||||
import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js';
|
||||
import { AsyncStore } from '../ts/logcontext.classes.asyncstore.js';
|
||||
|
||||
let testLogger = new logcontext.Logger('testNamespace');
|
||||
/**
|
||||
* This test file demonstrates how to use the AsyncContext and ensures
|
||||
* that runScoped() properly creates child AsyncStore contexts and merges parent data.
|
||||
*/
|
||||
|
||||
tap.test('should log for .error()', async () => {
|
||||
testLogger.error(new Error('first error message'));
|
||||
});
|
||||
const parentContext = new AsyncContext();
|
||||
|
||||
tap.test('should log for .fatal()', async () => {
|
||||
testLogger.fatal('this is fatal');
|
||||
});
|
||||
tap.test('should run a scoped function and add data to a child store', async () => {
|
||||
// add some default data to the parent store
|
||||
parentContext.store.add('parentKey', 'parentValue');
|
||||
expect(parentContext.store.get('parentKey')).toEqual('parentValue');
|
||||
|
||||
// set up independent log context
|
||||
tap.testParallel('should create an async LogContext', async (tools) => {
|
||||
testLogger.scope(async () => {
|
||||
testLogger.logmap.addData('id1', {
|
||||
someData: 'someValue',
|
||||
});
|
||||
await tools.delayFor(10).then(async () => {
|
||||
testLogger.log('hi');
|
||||
testLogger.error(new Error('custom error message'));
|
||||
});
|
||||
// now run a child scope, add some data, and check that parent's data is still accessible
|
||||
await parentContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('childKey', 'childValue');
|
||||
|
||||
// child should see its own data
|
||||
expect(childStore.get('childKey')).toEqual('childValue');
|
||||
// child should also see parent data
|
||||
expect(childStore.get('parentKey')).toEqual('parentValue');
|
||||
});
|
||||
});
|
||||
|
||||
tap.testParallel('should create a new scope', async () => {
|
||||
testLogger.scope(async () => {
|
||||
testLogger.logmap.addData('id1', {
|
||||
someData: 'otherValue',
|
||||
tap.test('should not contaminate the parent store with child-only data', async () => {
|
||||
// create a new child scope
|
||||
await parentContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('temporaryKey', 'temporaryValue');
|
||||
expect(childStore.get('temporaryKey')).toEqual('temporaryValue');
|
||||
});
|
||||
testLogger.info('anything');
|
||||
// after the child scope finishes, 'temporaryKey' should not exist in the parent
|
||||
expect(parentContext.store.get('temporaryKey')).toBeUndefined();
|
||||
});
|
||||
|
||||
tap.test('should allow adding data in multiple scopes independently', async () => {
|
||||
// add data in first scope
|
||||
await parentContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('childKey1', 'childValue1');
|
||||
expect(childStore.get('childKey1')).toEqual('childValue1');
|
||||
});
|
||||
|
||||
// add data in second scope
|
||||
await parentContext.runScoped(async (childStore: AsyncStore) => {
|
||||
childStore.add('childKey2', 'childValue2');
|
||||
expect(childStore.get('childKey2')).toEqual('childValue2');
|
||||
});
|
||||
|
||||
// neither childKey1 nor childKey2 should exist in the parent store
|
||||
expect(parentContext.store.get('childKey1')).toBeUndefined();
|
||||
expect(parentContext.store.get('childKey2')).toBeUndefined();
|
||||
});
|
||||
|
||||
tap.test('should allow deleting data in a child store without removing it from the parent store', async () => {
|
||||
// ensure parent has some data
|
||||
parentContext.store.add('deletableKey', 'iShouldStayInParent');
|
||||
|
||||
await parentContext.runScoped(async (childStore: AsyncStore) => {
|
||||
// child sees the parent's data
|
||||
expect(childStore.get('deletableKey')).toEqual('iShouldStayInParent');
|
||||
// attempt to delete it in the child
|
||||
childStore.delete('deletableKey');
|
||||
// child no longer sees it
|
||||
expect(childStore.get('deletableKey')).toBeUndefined();
|
||||
// but parent still has it
|
||||
expect(parentContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should log within default scope', async (tools) => {
|
||||
await tools.delayFor(3000);
|
||||
testLogger.log('message without context');
|
||||
tap.test('should allow multiple child scopes to share the same parent store data', async () => {
|
||||
// add a key to the parent store
|
||||
parentContext.store.add('sharedKey', 'sharedValue');
|
||||
expect(parentContext.store.get('sharedKey')).toEqual('sharedValue');
|
||||
|
||||
// first child scope
|
||||
await parentContext.runScoped(async (firstChild: AsyncStore) => {
|
||||
expect(firstChild.get('sharedKey')).toEqual('sharedValue');
|
||||
});
|
||||
|
||||
// second child scope
|
||||
await parentContext.runScoped(async (secondChild: AsyncStore) => {
|
||||
expect(secondChild.get('sharedKey')).toEqual('sharedValue');
|
||||
});
|
||||
});
|
||||
|
||||
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/smartcontext',
|
||||
version: '2.1.0',
|
||||
description: 'A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.'
|
||||
}
|
@ -1 +1 @@
|
||||
export * from './logcontext.classes.logger';
|
||||
export * from './logcontext.classes.asynccontext.js';
|
||||
|
13
ts/logcontext.classes.asynccontext.ts
Normal file
13
ts/logcontext.classes.asynccontext.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import * as plugins from './logcontext.plugins.js';
|
||||
import { AsyncStore } from './logcontext.classes.asyncstore.js';
|
||||
|
||||
export class AsyncContext {
|
||||
private context = new plugins.simpleAsyncContext.AsyncContext.Variable<AsyncStore>();
|
||||
public store = new AsyncStore();
|
||||
public runScoped(functionArg: (storeArg: AsyncStore) => Promise<void>) {
|
||||
this.context.run(this.store, async () => {
|
||||
const childStore = new AsyncStore(this.store);
|
||||
functionArg(childStore)
|
||||
});
|
||||
}
|
||||
}
|
50
ts/logcontext.classes.asyncstore.ts
Normal file
50
ts/logcontext.classes.asyncstore.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import * as plugins from './logcontext.plugins.js';
|
||||
|
||||
export class AsyncStore {
|
||||
private parentStore?: AsyncStore;
|
||||
private deletedKeys: string[] = [];
|
||||
private dataObject: {[key: string]: any} = {};
|
||||
|
||||
constructor(parentStore?: AsyncStore) {
|
||||
this.parentStore = parentStore;
|
||||
}
|
||||
|
||||
private cleanUp() {
|
||||
for (const key of this.deletedKeys) {
|
||||
if (this.parentStore && this.parentStore.get(key)) {
|
||||
// ok still valid
|
||||
} else {
|
||||
delete this.deletedKeys[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public add(keyArg: string, objectArg: any) {
|
||||
this.cleanUp();
|
||||
if (this.deletedKeys.includes(keyArg)) {
|
||||
this.deletedKeys = this.deletedKeys.filter((key) => key !== keyArg);
|
||||
}
|
||||
this.dataObject[keyArg] = objectArg;
|
||||
}
|
||||
|
||||
public delete(paramName: string) {
|
||||
this.cleanUp();
|
||||
if (this.parentStore.get(paramName)) {
|
||||
this.deletedKeys.push(paramName);
|
||||
}
|
||||
delete this.dataObject[paramName];
|
||||
}
|
||||
|
||||
public get(paramName: string) {
|
||||
this.cleanUp();
|
||||
if (this.deletedKeys.includes(paramName)) {
|
||||
return undefined;
|
||||
}
|
||||
return this.dataObject[paramName] || this.parentStore?.get(paramName);
|
||||
}
|
||||
|
||||
public getAll() {
|
||||
this.cleanUp();
|
||||
return {...this.dataObject, ...(this.parentStore?.getAll() || {})};
|
||||
}
|
||||
}
|
@ -1,124 +0,0 @@
|
||||
import * as plugins from './logcontext.plugins';
|
||||
import { LogMap } from './logcontext.classes.logmap';
|
||||
|
||||
export class Logger {
|
||||
namespaceString: string;
|
||||
smartcls: plugins.smartcls.SmartCls;
|
||||
logmap: LogMap;
|
||||
thirdPartyLogger: any;
|
||||
child: any;
|
||||
settings = {
|
||||
enableScope: () => {
|
||||
this.settingsParams.scope = true;
|
||||
},
|
||||
disableScope: () => {
|
||||
this.settingsParams.scope = false;
|
||||
},
|
||||
enableAddData: () => {
|
||||
this.settingsParams.addData = true;
|
||||
},
|
||||
disableAddData: () => {
|
||||
this.settingsParams.addData = false;
|
||||
},
|
||||
};
|
||||
private settingsParams: { scope: boolean; addData: boolean } = {
|
||||
scope: true,
|
||||
addData: true,
|
||||
};
|
||||
|
||||
constructor(namespaceArg: string = plugins.smartunique.shortId()) {
|
||||
this.namespaceString = namespaceArg;
|
||||
this.smartcls = new plugins.smartcls.SmartCls();
|
||||
this.logmap = new LogMap(this.smartcls);
|
||||
}
|
||||
|
||||
addData(paramNameArg: string, dataArg: any) {
|
||||
if (this.settingsParams.addData) {
|
||||
this.logmap.addData(paramNameArg, dataArg);
|
||||
}
|
||||
}
|
||||
|
||||
addThirdPartyLogger(thirdPartyLoggerArg) {
|
||||
this.thirdPartyLogger = thirdPartyLoggerArg;
|
||||
}
|
||||
|
||||
/**
|
||||
* debug
|
||||
* @param logMessageArg
|
||||
*/
|
||||
debug(logMessageArg) {
|
||||
this.routeLog('debug', logMessageArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* log
|
||||
* @param logMessageArg
|
||||
*/
|
||||
log(logMessageArg) {
|
||||
this.routeLog('log', logMessageArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* info
|
||||
* @param logObjectArg
|
||||
*/
|
||||
info(logObjectArg) {
|
||||
this.routeLog('info', logObjectArg);
|
||||
}
|
||||
|
||||
/**
|
||||
* error
|
||||
* @param logMessageArg
|
||||
* @param args
|
||||
*/
|
||||
error(logMessageArg, ...args) {
|
||||
this.routeLog('error', logMessageArg, ...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* warn
|
||||
* @param logMessageArg
|
||||
* @param args
|
||||
*/
|
||||
warn(logMessageArg, ...args) {
|
||||
this.routeLog('warn', logMessageArg, ...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* fatal
|
||||
* @param logMessageArg
|
||||
* @param args
|
||||
*/
|
||||
fatal(logMessageArg, ...args) {
|
||||
this.routeLog('fatal', logMessageArg, ...args);
|
||||
}
|
||||
|
||||
// creates a new async scope
|
||||
scope(funcArg: any) {
|
||||
// create node continuation scope
|
||||
if (this.settingsParams.scope) {
|
||||
this.smartcls.run(funcArg);
|
||||
} else {
|
||||
funcArg();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* routes the log according to whats available in the environment
|
||||
* @param {string} logMethod
|
||||
* @param {any} message
|
||||
* @param {any[]} ...args
|
||||
*/
|
||||
private routeLog(logMethod, message, ...args) {
|
||||
const logObject = {
|
||||
message: message,
|
||||
type: logMethod,
|
||||
logContext: this.logmap.getAllData(),
|
||||
};
|
||||
if (this.thirdPartyLogger && this.thirdPartyLogger[logMethod]) {
|
||||
this.thirdPartyLogger[logMethod](logObject, ...args);
|
||||
} else {
|
||||
console.log(logObject);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,31 +0,0 @@
|
||||
import * as plugins from './logcontext.plugins';
|
||||
|
||||
export class LogMap {
|
||||
smartcls: plugins.smartcls.SmartCls;
|
||||
paramMap = new plugins.lik.Stringmap();
|
||||
|
||||
constructor(clsNamespaceArg: plugins.smartcls.SmartCls) {
|
||||
this.smartcls = clsNamespaceArg;
|
||||
}
|
||||
|
||||
addData(paramName: string, logData) {
|
||||
this.paramMap.addString(paramName);
|
||||
this.smartcls.set(paramName, logData);
|
||||
}
|
||||
|
||||
deleteData(paramName: string) {
|
||||
this.smartcls.set(paramName, null);
|
||||
}
|
||||
|
||||
getData(paramName: string) {
|
||||
return this.smartcls.get(paramName);
|
||||
}
|
||||
|
||||
getAllData() {
|
||||
const returnObject = {};
|
||||
for (const stringArg of this.paramMap.getStringArray()) {
|
||||
returnObject[stringArg] = this.smartcls.get(stringArg);
|
||||
}
|
||||
return returnObject;
|
||||
}
|
||||
}
|
@ -1,13 +1,10 @@
|
||||
// native scope
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
export {
|
||||
AsyncLocalStorage
|
||||
};
|
||||
|
||||
// pushrocks scope
|
||||
import * as lik from '@pushrocks/lik';
|
||||
import * as smartcls from '@pushrocks/smartcls';
|
||||
import * as smartunique from '@pushrocks/smartunique';
|
||||
import * as lik from '@push.rocks/lik';
|
||||
import * as smartunique from '@push.rocks/smartunique';
|
||||
|
||||
export { lik, smartcls, smartunique };
|
||||
export { lik, smartunique };
|
||||
|
||||
// third party scope
|
||||
import simpleAsyncContext from 'simple-async-context';
|
||||
|
||||
export { simpleAsyncContext };
|
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"
|
||||
]
|
||||
}
|
17
tslint.json
17
tslint.json
@ -1,17 +0,0 @@
|
||||
{
|
||||
"extends": ["tslint:latest", "tslint-config-prettier"],
|
||||
"rules": {
|
||||
"semicolon": [true, "always"],
|
||||
"no-console": false,
|
||||
"ordered-imports": false,
|
||||
"object-literal-sort-keys": false,
|
||||
"member-ordering": {
|
||||
"options":{
|
||||
"order": [
|
||||
"static-method"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"defaultSeverity": "warning"
|
||||
}
|
Reference in New Issue
Block a user