@rollercoaster-dev/rd-logger
Version:
A neurodivergent-friendly logger for Rollercoaster.dev projects
60 lines (59 loc) • 3.02 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { Logger } from '../core/logger.service';
import { runWithRequestContext, getRequestStore, } from '../core/request-context';
/**
* Runs a function within a generic, uniquely identified logging context.
* Useful for background jobs, scripts, or any non-web task where grouped logging is desired.
*
* @template T The return type of the function being executed.
* @param fn The asynchronous function to execute within the context.
* @param options Configuration options for the generic context.
* @returns A promise that resolves with the return value of the executed function.
*/
export function runWithGenericContext(fn_1) {
return __awaiter(this, arguments, void 0, function* (fn, options = {}) {
const logger = options.loggerInstance || new Logger(options.loggerOptions);
const logStartEnd = options.logStartEnd !== false; // Default to true
const contextName = options.contextName || 'GenericContext';
// Wrap the execution in our core request context function
return runWithRequestContext(() => __awaiter(this, void 0, void 0, function* () {
const store = getRequestStore();
const requestId = store.requestId;
const startTime = store.requestStartTime;
try {
if (logStartEnd) {
logger.info(`▶ Starting ${contextName}`, { contextName, requestId });
}
const result = yield fn();
if (logStartEnd) {
const duration = Date.now() - startTime;
logger.info(`◀ Finished ${contextName}`, {
contextName,
requestId,
duration: `${duration}ms`,
});
}
return result;
}
catch (error) {
const duration = Date.now() - startTime;
logger.error(`💥 Error in ${contextName}`, {
contextName,
requestId,
duration: `${duration}ms`,
error: error, // Pass the raw error object
});
// Re-throw the error after logging
throw error;
}
}), options.requestId); // Pass optional existing request ID
});
}