UNPKG

@loglayer/context-manager-linked

Version:

Context manager for loglayer that keeps context between parent and all children.

65 lines (62 loc) 2.08 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); var _class;// src/LinkedContextManager.ts var LinkedContextManager = (_class = class _LinkedContextManager {constructor() { _class.prototype.__init.call(this); } __init() {this.contextContainer = { data: {}, hasContext: false }} /** * Sets the context data to be included with every log entry. Set to `undefined` to clear the context data. */ setContext(context) { if (!context) { for (const key in this.contextContainer.data) { if (Object.hasOwn(this.contextContainer.data, key)) { delete this.contextContainer.data[key]; } } this.contextContainer.hasContext = false; return; } Object.assign(this.contextContainer.data, context); this.contextContainer.hasContext = true; } /** * Appends context data to the existing context data. */ appendContext(context) { Object.assign(this.contextContainer.data, context); this.contextContainer.hasContext = true; } /** * Returns the context data to be included with every log entry. */ getContext() { return this.contextContainer.data; } /** * Returns true if context data is present. */ hasContextData() { return this.contextContainer.hasContext; } /** * Links the child context manager's context to be the same as the parent context manager's context. */ onChildLoggerCreated({ parentContextManager, childContextManager }) { if (childContextManager instanceof _LinkedContextManager) { childContextManager.contextContainer = this.contextContainer; } else { childContextManager.setContext(this.getContext()); } } /** * Creates a new instance of the context manager that shares the same context data. * The clone maintains a bi-directional link with the original context manager. */ clone() { const clone = new _LinkedContextManager(); clone.contextContainer = this.contextContainer; return clone; } }, _class); exports.LinkedContextManager = LinkedContextManager;