11 Commits

Author SHA1 Message Date
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
19 changed files with 9062 additions and 3467 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,128 +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
before_script:
- pnpm install -g pnpm
- pnpm install -g @shipzone/npmci
- npmci npm prepare
# ====================
# security stage
# ====================
# ====================
# security stage
# ====================
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --prod
tags:
- lossless
- docker
allow_failure: true
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --dev
tags:
- lossless
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci node install stable
- npmci npm install
- npmci npm 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 typescript
- npmci npm prepare
- npmci npm install
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install stable
- npmci npm install
- npmci command npm run buildDocs
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

57
changelog.md Normal file
View 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

View File

@ -2,16 +2,30 @@
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "logcontext",
"description": "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"
}
}

View File

@ -1,9 +1,11 @@
{
"name": "@pushrocks/logcontext",
"version": "1.0.29",
"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": {
@ -12,19 +14,20 @@
"buildDocs": "tsdoc"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.27",
"@gitzone/tsbundle": "^2.0.7",
"@gitzone/tsrun": "^1.2.39",
"@gitzone/tstest": "^1.0.57",
"@pushrocks/smartdelay": "^2.0.13",
"@pushrocks/tapbundle": "^5.0.4",
"@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": "^6.0.0",
"@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": [
@ -42,5 +45,23 @@
"npmextra.json",
"readme.md"
],
"type": "module"
"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"
}
}

11418
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

290
readme.md
View File

@ -1,82 +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 | [![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)
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. Lets 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, its 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')}`);
});
}
}
const mainContext = new AsyncContext();
processUserRequests(['alice', 'bob'], mainContext);
```
Each users 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
const newContext = new AsyncContext();
await newContext.runScoped(async (childStore: AsyncStore) => {
// This affects only the child store
childStore.add('childMessage', 'I am a child.');
// 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)
```
This approach helps you maintain clarity on what data belongs to the parent vs. a transient child operation.
#### Parallel Scopes
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:
```typescript
import { AsyncContext } from '@push.rocks/smartcontext';
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...
});
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');
};
await Promise.all([
handleUserLogin('user123', userContext),
handleUserLogin('user456', userContext),
]);
```
## class Logger
In this example, the `userContext` store data (like `appVersion`) is accessible within each child scope, but each user session remains isolated. The parents 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
import { Logger } from 'logcontext';
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}`);
}
}
// 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');
});
const loggingContext = new AsyncContext();
performTaskWithLogging('task_789', loggingContext);
```
## Contribution
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.
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). :)
### Managing Contexts Across Modules
For further information read the linked docs at the top of this readme.
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:
## Legal
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
```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. Heres 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 modules functionality, and tailor it to meet your projects 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.

View File

@ -1,41 +1,88 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as logcontext from '../ts/index.js';
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('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('paramName1', {
someData: 'someValue',
});
await tools.delayFor(10).then(async () => {
testLogger.log('hi');
testLogger.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',
});
testLogger.info('anything');
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');
});
// 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 (toolsArg) => {
await toolsArg.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();
tap.start();

View File

@ -1,8 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@pushrocks/logcontext',
version: '1.0.29',
description: 'enrich logs with context'
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.'
}

View File

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

View 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)
});
}
}

View 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() || {})};
}
}

View File

@ -1,123 +0,0 @@
import * as plugins from './logcontext.plugins.js';
import { LogMap } from './logcontext.classes.logmap.js';
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.js';
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 +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 };

View File

@ -3,8 +3,14 @@
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "nodenext",
"esModuleInterop": true
}
}
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"baseUrl": ".",
"paths": {}
},
"exclude": [
"dist_*/**/*.d.ts"
]
}