UNPKG

@loglayer/context-manager

Version:

Base context manager used to implement context managers for loglayer.

102 lines (99 loc) 2.54 kB
//#region src/DefaultContextManager.ts /** * The default context manager used by LogLayer. It is a simple k/v store for context data. * * @see {@link https://loglayer.dev/context-managers/default.html | Default Context Manager Docs} */ var DefaultContextManager = class DefaultContextManager { context = {}; 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) { this.context = {}; this.hasContext = false; return; } this.context = context; this.hasContext = true; } /** * Appends context data to the existing context data. */ appendContext(context) { this.context = { ...this.context, ...context }; this.hasContext = true; } /** * Returns the context data to be included with every log entry. */ getContext() { return this.context; } /** * Returns true if context data is present. */ hasContextData() { return this.hasContext; } /** * Clears the context data. If keys are provided, only those keys will be removed. * If no keys are provided, all context data will be cleared. */ clearContext(keys) { if (keys === void 0) { this.context = {}; this.hasContext = false; return; } const keysToRemove = Array.isArray(keys) ? keys : [keys]; for (const key of keysToRemove) delete this.context[key]; this.hasContext = Object.keys(this.context).length > 0; } /** * Copies the parent context data to the child context data. */ onChildLoggerCreated({ parentContextManager, childContextManager }) { if (parentContextManager.hasContextData()) { const parentContext = parentContextManager.getContext(); childContextManager.setContext({ ...parentContext }); } } /** * Creates a new instance of the context manager with the same context data. */ clone() { const clone = new DefaultContextManager(); clone.setContext({ ...this.context }); clone.hasContext = this.hasContext; return clone; } }; //#endregion //#region src/MockContextManager.ts /** * A mock context manager that does nothing. Useful for use with unit testing. */ var MockContextManager = class MockContextManager { setContext(_context) {} appendContext(_context) {} getContext() { return {}; } hasContextData() { return false; } clearContext(_keys) {} onChildLoggerCreated(_params) {} clone() { return new MockContextManager(); } }; //#endregion exports.DefaultContextManager = DefaultContextManager; exports.MockContextManager = MockContextManager;