UNPKG

@loglayer/context-manager-linked

Version:

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

65 lines (64 loc) 1.89 kB
// src/LinkedContextManager.ts var LinkedContextManager = class _LinkedContextManager { 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; } }; export { LinkedContextManager };