Compare commits

...

33 Commits

Author SHA1 Message Date
7f09f1b6f4 2.2.1 2025-01-25 01:23:27 +01:00
842784f2ee fix(core): Remove unused logcontext classes and update exports 2025-01-25 01:23:27 +01:00
8ba3b9085b 2.2.0 2025-01-25 01:22:12 +01:00
b0b4de3ab3 feat(tests): Added a new test script to demonstrate and validate AsyncContext functionality 2025-01-25 01:22:11 +01:00
33e2d01aca 2.1.8 2025-01-23 20:11:40 +01:00
c829b9c41e fix(core): Refactor and clean up class imports and exports 2025-01-23 20:11:40 +01:00
6332bf671a 2.1.7 2025-01-23 20:06:18 +01:00
6a373a93b3 fix(core): Enhanced debugging and improved dependency tracking 2025-01-23 20:06:18 +01:00
57d1dc3fe0 2.1.6 2025-01-19 20:06:19 +01:00
98f6afec7e fix(core): Updated dependencies and improved AsyncStore debugging and cleanup 2025-01-19 20:06:18 +01:00
8548ad9684 2.1.5 2025-01-19 11:15:46 +01:00
702fbcbded fix(dependencies): Update dependencies for improved compatibility 2025-01-19 11:15:46 +01:00
62b2f976cf 2.1.4 2025-01-19 00:30:21 +01:00
39ec78f358 fix(documentation): Remove unnecessary conclusion section from the README for better clarity. 2025-01-19 00:30:21 +01:00
f0c6b96648 2.1.3 2025-01-19 00:29:01 +01:00
18f63b07f7 fix(readme): Update README.md for better clarity and examples. 2025-01-19 00:29:00 +01:00
36d52a9e03 2.1.2 2025-01-19 00:27:07 +01:00
9c0b53f373 fix(core): Improve scope handling in async contexts. 2025-01-19 00:27:06 +01:00
58b189c1c7 2.1.1 2025-01-18 23:53:15 +01:00
b246894060 fix(build): Fix tsbuild script to include missing flag 2025-01-18 23:53:15 +01:00
3d0fc6adc5 2.1.0 2025-01-18 23:52:44 +01:00
d16e3b613c feat(ci): Add GitHub Actions workflows for CI/CD 2025-01-18 23:52:44 +01:00
af18c2f57a update description 2024-05-29 14:11:16 +02:00
9476ad8129 update tsconfig 2024-04-14 13:39:41 +02:00
d1284024d5 update npmextra.json: githost 2024-04-01 21:33:20 +02:00
0114de2690 update npmextra.json: githost 2024-04-01 19:57:28 +02:00
011f8427c1 update npmextra.json: githost 2024-03-30 21:46:24 +01:00
3866cb9580 switch to new org scheme 2023-07-11 00:01:09 +02:00
31140af566 switch to new org scheme 2023-07-10 02:41:36 +02:00
c4b9833145 2.0.0 2023-01-12 11:59:41 +01:00
3c6d217563 BREAKING CHANGE(switch to esm): update 2023-01-12 11:59:41 +01:00
8524299d39 1.0.29 2023-01-12 11:58:35 +01:00
227931b0d3 fix(core): update 2023-01-12 11:58:34 +01:00
32 changed files with 10645 additions and 27663 deletions

View 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

View 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
View File

@ -3,7 +3,6 @@
# artifacts
coverage/
public/
pages/
# installs
node_modules/
@ -17,4 +16,4 @@ node_modules/
dist/
dist_*/
# custom
#------# custom

View File

@ -1,138 +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
only:
- tags
tags:
- lossless
- docker
- notpriv
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
allow_failure: true
auditDevDependencies:
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 --only=dev
tags:
- docker
allow_failure: true
# ====================
# 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:
- docker
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:
- docker
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
only:
- tags
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

123
changelog.md Normal file
View File

@ -0,0 +1,123 @@
# Changelog
## 2025-01-25 - 2.2.1 - fix(core)
Remove unused logcontext classes and update exports
- Removed classes and plugins from logcontext that were not in use.
- Adjusted exports to not include deprecated logger-related modules.
## 2025-01-25 - 2.2.0 - feat(tests)
Added a new test script to demonstrate and validate AsyncContext functionality
- Introduced jstrial.js in the test directory to ensure the correct working of AsyncContext.
- The new tests handle various scenarios, including the independence of child stores and data deletion.
## 2025-01-23 - 2.1.8 - fix(core)
Refactor and clean up class imports and exports
- Simplified class file structure by unifying imports and exports.
- Removed redundant `logcontext.*` prefixes from filenames.
- Ensured consistent path references in index.ts.
## 2025-01-23 - 2.1.7 - fix(core)
Enhanced debugging and improved dependency tracking
- Updated @types/node to version ^22.10.10.
- Updated simple-async-context to version ^0.0.23.
- Enhanced the logDebug method to check for the existence of process and environment variables.
- Fixed dependency versions in package.json.
## 2025-01-19 - 2.1.6 - fix(core)
Updated dependencies and improved AsyncStore debugging and cleanup
- Upgraded 'simple-async-context' dependency to version ^0.0.16 for consistency and improvements.
- Added detailed debugging information in AsyncStore when DEBUG environment variable is set.
- Enhanced cleanup process for deleted keys in AsyncStore.
- Removed redundant dependencies from package.json and logcontext.plugins.ts.
## 2025-01-19 - 2.1.5 - fix(dependencies)
Update dependencies for improved compatibility
- Updated @types/node to version ^22.10.7
- Updated @types/shortid to version 2.2.0
- Updated simple-async-context to version ^0.0.15
## 2025-01-19 - 2.1.4 - fix(documentation)
Remove unnecessary conclusion section from the README for better clarity.
- Removed the 'Conclusion' header which was redundant in the README.
## 2025-01-19 - 2.1.3 - fix(readme)
Update README.md for better clarity and examples.
- Enhanced documentation with clearer examples of AsyncContext usage.
- Reorganized sections for improved understanding of `runScoped` and its benefits.
- Added detailed test script example in README.md.
- Clarified data isolation and deletion mechanisms within scoped functions.
## 2025-01-19 - 2.1.2 - fix(core)
Improve scope handling in async contexts.
- Modified the handling of scoped stores within `AsyncContext.runScoped` to simplify the API usage.
- Refactored tests to verify the context's behavior and isolation between parent and child stores.
## 2025-01-18 - 2.1.1 - fix(build)
Fix tsbuild script to include missing flag
- Updated the build script in package.json to include --allowimplicitany flag.
## 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

1
dist/index.d.ts vendored
View File

@ -1 +0,0 @@
export * from './logcontext.classes.logger';

7
dist/index.js vendored
View File

@ -1,7 +0,0 @@
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./logcontext.classes.logger"));
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLGlEQUE0QyJ9

View File

@ -1,60 +0,0 @@
import * as plugins from './logcontext.plugins';
import { LogMap } from './logcontext.classes.logmap';
export declare class Logger {
namespaceString: string;
clsNameSpace: plugins.smartcls.Namespace;
logmap: LogMap;
thirdPartyLogger: any;
child: any;
settings: {
enableScope: () => void;
disableScope: () => void;
enableAddData: () => void;
disableAddData: () => void;
};
private settingsParams;
constructor(namespaceArg?: string);
addData(paramNameArg: string, dataArg: any): void;
addThirdPartyLogger(thirdPartyLoggerArg: any): void;
/**
* debug
* @param logMessageArg
*/
debug(logMessageArg: any): void;
/**
* log
* @param logMessageArg
*/
log(logMessageArg: any): void;
/**
* info
* @param logObjectArg
*/
info(logObjectArg: any): void;
/**
* error
* @param logMessageArg
* @param args
*/
error(logMessageArg: any, ...args: any[]): void;
/**
* warn
* @param logMessageArg
* @param args
*/
warn(logMessageArg: any, ...args: any[]): void;
/**
* fatal
* @param logMessageArg
* @param args
*/
fatal(logMessageArg: any, ...args: any[]): void;
scope(funcArg: any): void;
/**
* routes the log according to whats available in the environment
* @param {string} logMethod
* @param {any} message
* @param {any[]} ...args
*/
private routeLog(logMethod, message, ...args);
}

View File

@ -1,113 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const plugins = require("./logcontext.plugins");
const logcontext_classes_logmap_1 = require("./logcontext.classes.logmap");
class Logger {
constructor(namespaceArg = plugins.shortid()) {
this.settings = {
enableScope: () => {
this.settingsParams.scope = true;
},
disableScope: () => {
this.settingsParams.scope = false;
},
enableAddData: () => {
this.settingsParams.addData = true;
},
disableAddData: () => {
this.settingsParams.addData = false;
}
};
this.settingsParams = {
scope: true,
addData: true
};
this.namespaceString = namespaceArg;
this.clsNameSpace = plugins.smartcls.createNamespace(this.namespaceString);
this.logmap = new logcontext_classes_logmap_1.LogMap(this.clsNameSpace);
}
addData(paramNameArg, dataArg) {
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) {
// create node continuation scope
if (this.settingsParams.scope) {
this.clsNameSpace.run(funcArg);
}
else {
funcArg();
}
}
/**
* routes the log according to whats available in the environment
* @param {string} logMethod
* @param {any} message
* @param {any[]} ...args
*/
routeLog(logMethod, message, ...args) {
let logObject = {
message: message,
type: logMethod,
logContext: this.logmap.getAllData()
};
if (this.thirdPartyLogger && this.thirdPartyLogger[logMethod]) {
this.thirdPartyLogger[logMethod](logObject, ...args);
}
else {
console.log(logObject);
}
}
}
exports.Logger = Logger;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjoz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yxDQUFDLENBQUM7UUFDekIsQ0FBQztJQUNILENBQUM7Q0FDRjtBQXhIRCx3QkF3SEMifQ==

View File

@ -1,11 +0,0 @@
import * as plugins from './logcontext.plugins';
import { Namespace } from 'smartcls';
export declare class LogMap {
clsNamespace: Namespace;
paramMap: plugins.lik.Stringmap;
constructor(clsNamespaceArg: Namespace);
addData(paramName: string, logData: any): void;
deleteData(paramName: string): void;
getData(paramName: string): any;
getAllData(): {};
}

View File

@ -1,28 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const plugins = require("./logcontext.plugins");
class LogMap {
constructor(clsNamespaceArg) {
this.paramMap = new plugins.lik.Stringmap();
this.clsNamespace = clsNamespaceArg;
}
addData(paramName, logData) {
this.paramMap.addString(paramName);
this.clsNamespace.set(paramName, logData);
}
deleteData(paramName) {
this.clsNamespace.set(paramName, null);
}
getData(paramName) {
return this.clsNamespace.get(paramName);
}
getAllData() {
let returnObject = {};
for (let stringArg of this.paramMap.getStringArray()) {
returnObject[stringArg] = this.clsNamespace.get(stringArg);
}
return returnObject;
}
}
exports.LogMap = LogMap;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9nY29udGV4dC5jbGFzc2VzLmxvZ21hcC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3RzL2xvZ2NvbnRleHQuY2xhc3Nlcy5sb2dtYXAudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxnREFBZ0Q7QUFLaEQ7SUFJRSxZQUFZLGVBQTBCO1FBRnRDLGFBQVEsR0FBRyxJQUFJLE9BQU8sQ0FBQyxHQUFHLENBQUMsU0FBUyxFQUFFLENBQUM7UUFHckMsSUFBSSxDQUFDLFlBQVksR0FBRyxlQUFlLENBQUM7SUFDdEMsQ0FBQztJQUVELE9BQU8sQ0FBQyxTQUFpQixFQUFFLE9BQU87UUFDaEMsSUFBSSxDQUFDLFFBQVEsQ0FBQyxTQUFTLENBQUMsU0FBUyxDQUFDLENBQUM7UUFDbkMsSUFBSSxDQUFDLFlBQVksQ0FBQyxHQUFHLENBQUMsU0FBUyxFQUFFLE9BQU8sQ0FBQyxDQUFDO0lBQzVDLENBQUM7SUFFRCxVQUFVLENBQUMsU0FBaUI7UUFDMUIsSUFBSSxDQUFDLFlBQVksQ0FBQyxHQUFHLENBQUMsU0FBUyxFQUFFLElBQUksQ0FBQyxDQUFDO0lBQ3pDLENBQUM7SUFFRCxPQUFPLENBQUMsU0FBaUI7UUFDdkIsTUFBTSxDQUFDLElBQUksQ0FBQyxZQUFZLENBQUMsR0FBRyxDQUFDLFNBQVMsQ0FBQyxDQUFDO0lBQzFDLENBQUM7SUFFRCxVQUFVO1FBQ1IsSUFBSSxZQUFZLEdBQUcsRUFBRSxDQUFDO1FBQ3RCLEdBQUcsQ0FBQyxDQUFDLElBQUksU0FBUyxJQUFJLElBQUksQ0FBQyxRQUFRLENBQUMsY0FBYyxFQUFFLENBQUMsQ0FBQyxDQUFDO1lBQ3JELFlBQVksQ0FBQyxTQUFTLENBQUMsR0FBRyxJQUFJLENBQUMsWUFBWSxDQUFDLEdBQUcsQ0FBQyxTQUFTLENBQUMsQ0FBQztRQUM3RCxDQUFDO1FBQ0QsTUFBTSxDQUFDLFlBQVksQ0FBQztJQUN0QixDQUFDO0NBQ0Y7QUE1QkQsd0JBNEJDIn0=

View File

@ -1,5 +0,0 @@
import 'typings-global';
import * as lik from 'lik';
import * as smartcls from 'smartcls';
import * as shortid from 'shortid';
export { lik, smartcls, shortid };

View File

@ -1,10 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("typings-global");
const lik = require("lik");
exports.lik = lik;
const smartcls = require("smartcls");
exports.smartcls = smartcls;
const shortid = require("shortid");
exports.shortid = shortid;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9nY29udGV4dC5wbHVnaW5zLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvbG9nY29udGV4dC5wbHVnaW5zLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsMEJBQXdCO0FBRXhCLDJCQUEyQjtBQUlsQixrQkFBRztBQUhaLHFDQUFxQztBQUd2Qiw0QkFBUTtBQUZ0QixtQ0FBbUM7QUFFWCwwQkFBTyJ9

View File

@ -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"
}
}

26976
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,30 +1,29 @@
{
"name": "@pushrocks/logcontext",
"version": "1.0.28",
"description": "enrich logs with context",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"name": "@push.rocks/smartcontext",
"version": "2.2.1",
"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 --allowimplicitany --web)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.27",
"@gitzone/tsbundle": "^1.0.87",
"@gitzone/tstest": "^1.0.57",
"@pushrocks/smartdelay": "^2.0.13",
"@pushrocks/tapbundle": "^3.2.14",
"@types/node": "^16.9.2",
"tslint": "^6.1.3",
"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.96",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/tapbundle": "^5.5.6",
"@types/node": "^22.10.10"
},
"dependencies": {
"@pushrocks/lik": "^4.0.22",
"@pushrocks/smartcls": "^1.0.9",
"@pushrocks/smartunique": "^3.0.3",
"@types/shortid": "0.0.29"
"simple-async-context": "^0.0.23"
},
"private": false,
"browserslist": [
@ -41,5 +40,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"
}
}

9670
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

259
readme.md
View File

@ -1,84 +1,221 @@
# @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
Special thanks to Ilias Bhallil for his awesome simple-async-context library.
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/logcontext/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/logcontext/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/logcontext)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/logcontext)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/logcontext)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/logcontext)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/logcontext)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
## Install
Make sure you have Node.js and npm installed, then run:
```bash
npm install @push.rocks/smartcontext
```
This will install the library and its dependencies into your local `node_modules` folder.
## Usage
Use TypeScript for best in class instellisense.
The `@push.rocks/smartcontext` module provides an efficient way to enrich your code (often for logging) with contextual information. It uses asynchronous context management to support hierarchical scopes—particularly helpful in complex or nested asynchronous operations in Node.js.
the logconext module exposes an easy to use syntax for nodejs style async logcontexts.
### Basic Setup
```typescript
let testLogger = new logcontext.Logger('testNamespace');
import { AsyncContext } from '@push.rocks/smartcontext';
testLogger.scope(async () => {
testLogger.addData('id1', {
someData: 'someValue',
});
testLogger.log('hi');
testLogger.error(new Error('custom error message'));
setTimeout(() => {
outsideFunction(); // log scope will travel through callbacks and promises
}, 2000);
});
const asyncContext = new AsyncContext();
let outsideFunction = () => {
// Note:
// the below testLogger reference will have different contexts
// depending from which scope "outsideFunction" was called".
testLogger.log('some message');
};
// The parent store is always accessible through `asyncContext.store`
asyncContext.store.add('username', 'john_doe');
console.log(asyncContext.store.get('username')); // 'john_doe'
```
## class Logger
### `runScoped`
When you call `asyncContext.runScoped(async () => { ... })`, the library automatically creates a **child** `AsyncStore`. Inside that scoped function, `asyncContext.store` refers to the child store. Any data you add or delete there is isolated from the parent store. However, you can still read parent data if it hasnt been overridden.
```typescript
import { Logger } from 'logcontext';
await asyncContext.runScoped(async () => {
// Inside this callback, `asyncContext.store` is a *child* store
asyncContext.store.add('transactionId', 'txn_abc123');
console.log(asyncContext.store.get('transactionId')); // 'txn_abc123'
// 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');
// We can also see parent data like 'username'
console.log(asyncContext.store.get('username')); // 'john_doe'
});
// Outside `runScoped`, asyncContext.store reverts to the parent store
console.log(asyncContext.store.get('transactionId')); // undefined
```
## Contribution
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). :)
### Isolating Data
For further information read the linked docs at the top of this readme.
Because each call to `runScoped` returns control to the parent store afterward, any keys added in a child scope disappear once the scope completes (unless you explicitly move them to the parent). This mechanism keeps data from leaking between scopes.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
```typescript
// Parent store
asyncContext.store.add('someParentKey', 'parentValue');
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
// Child scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('scopedKey', 'childValue');
console.log(asyncContext.store.get('scopedKey')); // 'childValue'
});
// Outside, the child key is gone
console.log(asyncContext.store.get('scopedKey')); // undefined
```
### Deleting Data
If the child deletes a key that exists in the parent, it will only remove it from the childs view of the store. Once the scope completes, the parent store is unaffected.
```typescript
asyncContext.store.add('deletableKey', 'originalValue');
await asyncContext.runScoped(async () => {
console.log(asyncContext.store.get('deletableKey')); // 'originalValue'
asyncContext.store.delete('deletableKey');
console.log(asyncContext.store.get('deletableKey')); // undefined in child
});
console.log(asyncContext.store.get('deletableKey')); // 'originalValue' remains in parent
```
### Parallel or Sequential Scopes
You can call `runScoped` multiple times, whether sequentially or in parallel (with `Promise.all`). Each invocation creates its own isolated child store, preventing data collisions across asynchronous tasks.
```typescript
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey1', 'childValue1');
console.log(asyncContext.store.get('childKey1')); // 'childValue1'
});
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
console.log(asyncContext.store.get('childKey2')); // 'childValue2'
});
// Both keys were added in separate scopes, so they won't exist in the parent
console.log(asyncContext.store.get('childKey1')); // undefined
console.log(asyncContext.store.get('childKey2')); // undefined
```
### Testing Example
The following is a complete test script (using [tapbundle](https://www.npmjs.com/package/@push.rocks/tapbundle)) demonstrating how child stores inherit data from the parent but remain isolated. After each scoped block, new child keys vanish, and any parent keys deleted inside the child remain intact in the parent.
```typescript
import { tap, expect } from '@push.rocks/tapbundle';
import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js';
const asyncContext = new AsyncContext();
tap.test('should run a scoped function and add data to a child store', async () => {
// Add some default data to the parent store
asyncContext.store.add('parentKey', 'parentValue');
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
// Now run a child scope, add some data, and check that parent data is still accessible
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey', 'childValue');
// Child sees its own data
expect(asyncContext.store.get('childKey')).toEqual('childValue');
// Child also sees parent data
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
});
});
tap.test('should not contaminate the parent store with child-only data', async () => {
// Create a new child scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('temporaryKey', 'temporaryValue');
expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
});
// After scope finishes, 'temporaryKey' won't exist in the parent
expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
});
tap.test('should allow adding data in multiple scopes independently', async () => {
// Add data in the first scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey1', 'childValue1');
expect(asyncContext.store.get('childKey1')).toEqual('childValue1');
});
// Add data in the second scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
expect(asyncContext.store.get('childKey2')).toEqual('childValue2');
});
// Neither childKey1 nor childKey2 should exist in the parent store
expect(asyncContext.store.get('childKey1')).toBeUndefined();
expect(asyncContext.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
asyncContext.store.add('deletableKey', 'iShouldStayInParent');
await asyncContext.runScoped(async () => {
// Child sees the parent's data
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
// Delete it in the child
asyncContext.store.delete('deletableKey');
// Child no longer sees it
expect(asyncContext.store.get('deletableKey')).toBeUndefined();
});
// Parent still has it
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
});
tap.test('should allow multiple child scopes to share the same parent store data', async () => {
// Add a key to the parent store
asyncContext.store.add('sharedKey', 'sharedValue');
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
// First child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
// Second child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
});
export default tap.start();
```
With this updated `runScoped` design, theres no need to explicitly instantiate or manage child stores. The context automatically switches from the parent store to the child store while within the callback, then reverts back to the parent store afterwards. This structure makes it easy to:
- Keep each async operations state isolated
- Preserve read-access to parent context data
- Avoid overwriting or polluting other operations data
This pattern works particularly well for logging or any scenario where you need to pass metadata through deeply nested async calls without manually juggling that data everywhere in your code.
## License and Legal Information
This repository is under the [MIT License](./license). Please note that the MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as necessary for reasonable use in describing the origin of the work.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. 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, please contact us at hello@task.vc. By using this repository, you acknowledge that you have read this section and agree to comply with its terms.

110
test/jstrial.js Normal file
View File

@ -0,0 +1,110 @@
import { tap, expect } from '@push.rocks/tapbundle';
import * as asynccontext from '../dist_ts/index.js';
if (typeof process !== 'undefined') {
// process.env.DEBUG = 'true';
}
/**
* This test file demonstrates how to use the AsyncContext and ensures
* that runScoped() properly creates child AsyncStore contexts and merges parent data.
*/
const asyncContext = new asynccontext.AsyncContext();
tap.test('should run a scoped function and add data to a child store', async () => {
// add some default data to the parent store
asyncContext.store.add('parentKey', 'parentValue');
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
// now run a child scope, add some data, and check that parent's data is still accessible
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey', 'childValue');
// child should see its own data
expect(asyncContext.store.get('childKey')).toEqual('childValue');
// child should also see parent data
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
});
});
tap.test('should not contaminate the parent store with child-only data', async () => {
// create a new child scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('temporaryKey', 'temporaryValue');
expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
});
// after the child scope finishes, 'temporaryKey' should not exist in the parent
expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
});
tap.test('should allow adding data in multiple scopes independently', async (toolsArg) => {
const done = toolsArg.cumulativeDefer();
// add data in first scope
asyncContext.runScoped(async () => {
const subDone = done.subDefer();
asyncContext.store.add('childKey1', 'childValue1-v1');
await toolsArg.delayFor(2000);
expect(asyncContext.store.get('childKey1')).toEqual('childValue1-v1');
subDone.resolve();
});
asyncContext.runScoped(async () => {
const subDone = done.subDefer();
asyncContext.store.add('childKey1', 'childValue1-v2');
await toolsArg.delayFor(1000);
expect(asyncContext.store.get('childKey1')).toEqual('childValue1-v2');
subDone.resolve();
});
// add data in second scope
asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
expect(asyncContext.store.get('childKey2')).toEqual('childValue2');
});
// neither childKey1 nor childKey2 should exist in the parent store
expect(asyncContext.store.get('childKey1')).toBeUndefined();
expect(asyncContext.store.get('childKey2')).toBeUndefined();
await done.promise;
});
tap.test(
'should allow deleting data in a child store without removing it from the parent store',
async (toolsArg) => {
// ensure parent has some data
asyncContext.store.add('deletableKey', 'iShouldStayInParent');
await asyncContext.runScoped(async () => {
// child sees the parent's data
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
// attempt to delete it in the child
asyncContext.store.delete('deletableKey');
// child no longer sees it
expect(asyncContext.store.get('deletableKey')).toBeUndefined();
// but parent still has it
});
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
}
);
tap.test('should allow multiple child scopes to share the same parent store data', async () => {
// add a key to the parent store
asyncContext.store.add('sharedKey', 'sharedValue');
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
// first child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
// second child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
});
export default tap.start();

110
test/test.both.ts Normal file
View File

@ -0,0 +1,110 @@
import { tap, expect } from '@push.rocks/tapbundle';
import * as asynccontext from '../ts/index.js';
if (typeof process !== 'undefined') {
process.env.DEBUG = 'true';
}
/**
* This test file demonstrates how to use the AsyncContext and ensures
* that runScoped() properly creates child AsyncStore contexts and merges parent data.
*/
const asyncContext = new asynccontext.AsyncContext();
tap.test('should run a scoped function and add data to a child store', async () => {
// add some default data to the parent store
asyncContext.store.add('parentKey', 'parentValue');
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
// now run a child scope, add some data, and check that parent's data is still accessible
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey', 'childValue');
// child should see its own data
expect(asyncContext.store.get('childKey')).toEqual('childValue');
// child should also see parent data
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
});
});
tap.test('should not contaminate the parent store with child-only data', async () => {
// create a new child scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('temporaryKey', 'temporaryValue');
expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
});
// after the child scope finishes, 'temporaryKey' should not exist in the parent
expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
});
tap.test('should allow adding data in multiple scopes independently', async (toolsArg) => {
const done = toolsArg.cumulativeDefer();
// add data in first scope
asyncContext.runScoped(async () => {
const subDone = done.subDefer();
asyncContext.store.add('childKey1', 'childValue1-v1');
await toolsArg.delayFor(2000);
expect(asyncContext.store.get('childKey1')).toEqual('childValue1-v1');
subDone.resolve();
});
asyncContext.runScoped(async () => {
const subDone = done.subDefer();
asyncContext.store.add('childKey1', 'childValue1-v2');
await toolsArg.delayFor(1000);
expect(asyncContext.store.get('childKey1')).toEqual('childValue1-v2');
subDone.resolve();
});
// add data in second scope
asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
expect(asyncContext.store.get('childKey2')).toEqual('childValue2');
});
// neither childKey1 nor childKey2 should exist in the parent store
expect(asyncContext.store.get('childKey1')).toBeUndefined();
expect(asyncContext.store.get('childKey2')).toBeUndefined();
await done.promise;
});
tap.test(
'should allow deleting data in a child store without removing it from the parent store',
async (toolsArg) => {
// ensure parent has some data
asyncContext.store.add('deletableKey', 'iShouldStayInParent');
await asyncContext.runScoped(async () => {
// child sees the parent's data
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
// attempt to delete it in the child
asyncContext.store.delete('deletableKey');
// child no longer sees it
expect(asyncContext.store.get('deletableKey')).toBeUndefined();
// but parent still has it
});
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
}
);
tap.test('should allow multiple child scopes to share the same parent store data', async () => {
// add a key to the parent store
asyncContext.store.add('sharedKey', 'sharedValue');
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
// first child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
// second child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
});
export default tap.start();

View File

@ -1,41 +0,0 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as logcontext from '../ts/index';
let testLogger = new logcontext.Logger('testNamespace');
tap.test('should log for .error()', async () => {
testLogger.error('first error message');
});
tap.test('should log for .fatal()', async () => {
testLogger.fatal('this is fatal');
});
// set up independent log context
tap.testParallel('should create an async LogContext', async (tools) => {
testLogger.scope(async () => {
testLogger.logmap.addData('paramName1', {
someData: 'someValue',
});
await tools.delayFor(10).then(async () => {
testLogger.log('hi');
testLogger.error('custom error message');
});
});
});
tap.testParallel('should create a new scope', async () => {
testLogger.scope(async () => {
testLogger.logmap.addData('id1', {
someData: 'otherValue',
});
testLogger.info('anything');
});
});
tap.test('should log within default scope', async (tools) => {
await tools.delayFor(3000);
testLogger.log('message without context');
});
tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartcontext',
version: '2.2.1',
description: 'A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.'
}

View File

@ -0,0 +1,18 @@
import * as plugins from './plugins.js';
import { AsyncStore } from './classes.asyncstore.js';
export class AsyncContext {
private _context = new plugins.simpleAsyncContext.AsyncContext.Variable<AsyncStore>();
private _store = new AsyncStore();
get store() {
return this._context.get() || this._store;
}
set store(value: AsyncStore) {
this._store = value;
}
public async runScoped(functionArg: () => Promise<void>) {
await this._context.run(new AsyncStore(this.store), async () => {
await functionArg()
});
}
}

135
ts/classes.asyncstore.ts Normal file
View File

@ -0,0 +1,135 @@
import * as plugins from './plugins.js';
export class AsyncStore {
private static idCounter = 0;
private id: number;
private parentStore?: AsyncStore;
private deletedKeys: string[] = [];
private dataObject: { [key: string]: any } = {};
constructor(parentStore?: AsyncStore) {
this.parentStore = parentStore;
this.id = AsyncStore.idCounter++;
}
/**
* Logs debug info if process.env.DEBUG is set.
*/
private logDebug(functionName: string, before: Record<string, any>, after: Record<string, any>) {
if (typeof process !== 'undefined' && process.env && process.env.DEBUG) {
console.log(`Store ID: ${this.id}`);
console.log(`Function: ${functionName}`);
console.log('--- Before ---');
console.log(before);
console.log('--- After ---');
console.log(after);
console.log('-----------------------');
}
}
/**
* Cleans up the deleted keys if they no longer exist in any parent store.
*/
private cleanUp() {
for (const key of this.deletedKeys) {
if (this.parentStore && this.parentStore.get(key)) {
// Parent still has it, so keep in deletedKeys
} else {
const index = this.deletedKeys.indexOf(key);
if (index !== -1) {
this.deletedKeys.splice(index, 1);
}
}
}
}
/**
* Adds or updates a value under a specific key in this store.
*/
public add(keyArg: string, objectArg: any) {
// capture the before state
const before = { ...this.dataObject, deletedKeys: [...this.deletedKeys] };
this.cleanUp();
// If this key was previously deleted, remove it from deletedKeys.
if (this.deletedKeys.includes(keyArg)) {
this.deletedKeys = this.deletedKeys.filter((key) => key !== keyArg);
}
this.dataObject[keyArg] = objectArg;
// capture the after state
const after = { ...this.dataObject, deletedKeys: [...this.deletedKeys] };
this.logDebug('add', before, after);
}
/**
* Deletes a key from the current store.
* If a parent store has the key, we record it in `deletedKeys` so the child store "shadows" it.
*/
public delete(paramName: string) {
// capture the before state
const before = { ...this.dataObject, deletedKeys: [...this.deletedKeys] };
this.cleanUp();
if (this.parentStore?.get(paramName)) {
// The parent store has this key; let's mark it as deleted in the child
this.deletedKeys.push(paramName);
}
delete this.dataObject[paramName];
// capture the after state
const after = { ...this.dataObject, deletedKeys: [...this.deletedKeys] };
this.logDebug('delete', before, after);
}
/**
* Gets the value of a key, checking this store first, then the parent store if necessary.
* Will log the store state before/after for debugging.
*/
public get(paramName: string) {
// capture the before state
const before = { ...this.dataObject, deletedKeys: [...this.deletedKeys] };
this.cleanUp();
// figure out if paramName is deleted or present
let result: any;
if (this.deletedKeys.includes(paramName)) {
result = undefined;
} else {
result = this.dataObject[paramName] ?? this.parentStore?.get(paramName);
}
// capture the after state; we can also show the `result` in the log
const after = {
...this.dataObject,
deletedKeys: [...this.deletedKeys],
retrievedKey: paramName,
result
};
this.logDebug('get', before, after);
return result;
}
/**
* Returns all keys and values, merged with the parent store, but
* does NOT include keys that are "deleted" in the child.
* Child store should override parent if the same key exists in both.
*/
public getAll() {
this.cleanUp();
// first, get parent's data as a shallow copy
const parentData = { ...(this.parentStore?.getAll() || {}) };
// remove keys from parent data that this child has deleted
for (const key of this.deletedKeys) {
delete parentData[key];
}
// child's data overrides parent data for any matching keys
return {
...parentData,
...this.dataObject
};
}
}

View File

@ -1 +1,2 @@
export * from './logcontext.classes.logger';
export * from './classes.asynccontext.js';
export * from './classes.asyncstore.js';

View File

@ -1,123 +0,0 @@
import * as plugins from './logcontext.plugins';
import { LogMap } from './logcontext.classes.logmap';
export class Logger {
public namespaceString: string;
smartcls: plugins.smartcls.SmartCls;
public logmap: LogMap;
public thirdPartyLogger: 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: any) {
this.thirdPartyLogger = thirdPartyLoggerArg;
}
/**
* debug
* @param logMessageArg
*/
debug(logMessageArg: string) {
this.routeLog('debug', logMessageArg);
}
/**
* log
* @param logMessageArg
*/
log(logMessageArg: string) {
this.routeLog('log', logMessageArg);
}
/**
* info
* @param logMessageArg
*/
info(logMessageArg: string) {
this.routeLog('info', logMessageArg);
}
/**
* error
* @param logMessageArg
* @param args
*/
error(logMessageArg: string, ...args: any) {
this.routeLog('error', logMessageArg, ...args);
}
/**
* warn
* @param logMessageArg
* @param args
*/
warn(logMessageArg: string, ...args: any) {
this.routeLog('warn', logMessageArg, ...args);
}
/**
* fatal
* @param logMessageArg
* @param args
*/
fatal(logMessageArg: string, ...args: any) {
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} messageArg
* @param {any[]} ...args
*/
private routeLog(logMethod: string, messageArg: string, ...args: any) {
const logObject = {
message: messageArg,
type: logMethod,
logContext: this.logmap.getAllData(),
};
if (this.thirdPartyLogger && this.thirdPartyLogger[logMethod]) {
this.thirdPartyLogger[logMethod](logObject, ...args);
} else {
console.log(logObject);
}
}
}

View File

@ -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: any) {
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: any = {};
for (const stringArg of this.paramMap.getStringArray()) {
returnObject[stringArg] = this.smartcls.get(stringArg);
}
return returnObject;
}
}

View File

@ -1,11 +0,0 @@
// 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';
export { lik, smartcls, smartunique };

4
ts/plugins.ts Normal file
View File

@ -0,0 +1,4 @@
// third party scope
import simpleAsyncContext from 'simple-async-context';
export { simpleAsyncContext };

16
tsconfig.json Normal file
View 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"
]
}

View File

@ -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"
}