logctx
Version:
A Pino-based logger with context-aware logging using async_hooks
47 lines (46 loc) • 1.73 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getContext = exports.runWithContext = exports.configureLoggerContext = void 0;
const async_hooks_1 = require("async_hooks");
/**
* ContextManager is a utility class that provides a way to manage context
* across asynchronous calls using AsyncLocalStorage.
*
* @template T The type of the context.
*/
let store = new async_hooks_1.AsyncLocalStorage();
let getDefaultContext = () => ({});
/*
* Configure the default context getter function.
* This function is used to provide a default context when no context is set.
* It should return an object that represents the default context.
*
* @param contextGetter - A function that returns the default context object.
*/
function configureLoggerContext(contextGetter) {
getDefaultContext = contextGetter;
}
exports.configureLoggerContext = configureLoggerContext;
/**
* Runs a callback function with a specific context.
* The context is set using AsyncLocalStorage, allowing the callback to access
* the context throughout its execution.
*
* @param context - The context to run the callback with.
* @param callback - The callback function to execute with the provided context.
* @template T - The type of the context.
*/
function runWithContext(context, callback) {
store.run(context, callback);
}
exports.runWithContext = runWithContext;
/**
* Retrieves the current context from the AsyncLocalStorage.
* If no context is set, it returns the default context provided by `getDefaultContext`.
*
* @returns The current context or the default context if none is set.
*/
function getContext() {
return store.getStore() || getDefaultContext();
}
exports.getContext = getContext;