All files / src/logger prefixed-logger.ts

99.08% Statements 216/218
98.87% Branches 88/89
94.28% Functions 33/35
99.08% Lines 216/218

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 6351x   1x 1x   1x 1x 1x 1x                                                                                                                                                                                                                                                                                                         1x           616x 616x 616x                               616x 616x 157x 157x   459x 459x   459x 616x 265x 265x 265x 265x 616x 194x 194x 194x 91x 91x 194x   459x 459x 459x             1x 459x 459x 459x 459x 459x 459x   459x 748x 639x 639x   109x 109x 109x 748x   459x 748x 748x 748x 109x 109x 748x 748x   459x 459x 459x 459x 459x   459x 32x 32x   459x 116x 116x 116x   459x 2x 2x 459x 156x 156x   459x 12x 12x 459x 282x 282x   459x 76x 76x 459x 133x 133x   459x 3x 3x 459x 4x 4x   459x 9x 9x 9x 9x 9x 459x 6x 6x   459x 11x 11x 11x 11x 11x 459x 17x 17x   459x 2x 2x 2x 2x 2x 459x 3x 3x   459x 2x 2x 2x 2x 2x 459x 2x 2x   459x 3x 3x 3x 3x 3x 459x 4x 4x   459x 21x 21x 21x 21x   459x 459x 459x   459x 459x   1x 135x 45x 45x 135x 135x   1x 27x 27x 27x 27x 27x 27x 27x 27x   1x 1x 448x       448x 448x 448x 448x 448x   448x 448x                                                                                                                                     1x           223x 223x 223x                                                                                                                                                                   1x 14x 14x 14x                     14x 14x 14x 13x 13x 14x 14x               1x 763x 761x 340x 340x 340x 340x 340x 340x 340x                             1x 529x 332x 332x 332x 332x 332x 332x 197x                                 1x 3x 3x 3x 3x 3x 3x 3x   3x 3x                              
import { isNotNullable } from '../utils/common/is-not-nullable.ts';
import type { Logger, LogMessage, LogTemplateStringsArray } from './definition.ts';
import { BaseLogger } from './implementation/base-logger.ts';
import { OFF_LOGGER } from './off-logger.ts';
 
const prefixSymbol: unique symbol = Symbol.for('@emitnlog/logger/prefix');
const separatorSymbol: unique symbol = Symbol.for('@emitnlog/logger/separator');
const messageSeparatorSymbol: unique symbol = Symbol.for('@emitnlog/logger/messageSeparator');
const rootLoggerSymbol: unique symbol = Symbol.for('@emitnlog/logger/rootLogger');
 
/**
 * A specialized logger that prepends a fixed prefix to all log messages.
 *
 * The PrefixedLogger maintains all the functionality of a standard Logger while ensuring every log message is
 * automatically prefixed, making it easier to:
 *
 * - Categorize logs by component, module, or subsystem
 * - Distinguish logs from different parts of your application
 * - Create hierarchical logging structures with nested prefixes
 *
 * The prefix is strongly typed and, in some development environments, is visible on the logger's tooltip.
 */
export interface PrefixedLogger<TPrefix extends string = string, TSeparator extends string = string> extends Logger {
  /*
   * The prefix or undefined.
   */
  readonly [prefixSymbol]: TPrefix | undefined;
 
  /*
   * The value used to separate different parts of the prefix, or undefined
   */
  readonly [separatorSymbol]: TSeparator | undefined;
}
 
/**
 * Creates a new logger that prepends a specified prefix to all log messages.
 *
 * This function wraps an existing logger and returns a new logger instance where all log messages are automatically
 * prefixed. This is useful for categorizing logs or distinguishing between different components in your application.
 * The log level of a prefixed logger is always the same as its underlying logger.
 *
 * When applied to an already prefixed logger, it preserves the full prefix chain both at runtime and in the type
 * system, allowing for strongly-typed nested prefixes.
 *
 * @example Basic Usage
 *
 * ```ts
 * import { createConsoleLogLogger, withPrefix } from 'emitnlog/logger';
 *
 * const logger = createConsoleLogLogger('info');
 * const dbLogger = withPrefix(logger, 'DB');
 *
 * dbLogger.i`Connected to database`;
 * // Output: "DB: Connected to database"
 * ```
 *
 * @example Template Literals
 *
 * ```ts
 * import { withPrefix } from 'emitnlog/logger';
 *
 * const dbLogger = withPrefix(logger, 'DB');
 * const queryTime = 42;
 *
 * // Prefix is maintained with template literals
 * dbLogger.d`Query executed in ${queryTime}ms`;
 * // Output: "DB: Query executed in 42ms"
 * ```
 *
 * @example Nested Prefixes
 *
 * ```ts
 * import { withPrefix } from 'emitnlog/logger';
 *
 * const dbLogger = withPrefix(logger, 'DB');
 * const userDbLogger = withPrefix(dbLogger, 'users');
 * // Type of userDbLogger is PrefixedLogger<'DB.users'>
 *
 * const userId = 123;
 * userDbLogger.w`User not found: ${userId}`;
 * // Output: "DB.users: User not found: 123"
 * ```
 *
 * @example Error Handling
 *
 * ```ts
 * import { withPrefix } from 'emitnlog/logger';
 *
 * const dbLogger = withPrefix(logger, 'DB');
 *
 * // Errors maintain their original objects while prefixing the message
 * const error = new Error('Connection failed');
 * dbLogger.error(error);
 * // Output: "DB: Connection failed" (with error object preserved in args)
 *
 * // Using args() for additional context
 * dbLogger.args(error, { connectionId: 'conn_123' }).e`Database operation failed`;
 * ```
 *
 * @example Custom Separators
 *
 * ```ts
 * import { withPrefix } from 'emitnlog/logger';
 *
 * // Custom prefix separator
 * const apiLogger = withPrefix(logger, 'API', { prefixSeparator: '/' });
 * const v1Logger = withPrefix(apiLogger, 'v1');
 * v1Logger.i`Request processed`;
 * // Output: "API/v1: Request processed"
 *
 * // Custom message separator
 * const compactLogger = withPrefix(logger, 'SYS', { messageSeparator: ' | ' });
 * compactLogger.i`System ready`;
 * // Output: "SYS | System ready"
 * ```
 *
 * @example Fallback Prefix
 *
 * ```ts
 * import { withPrefix } from 'emitnlog/logger';
 *
 * // Add a fallback prefix when the logger isn't already prefixed
 * const serviceLogger = withPrefix(logger, 'UserService', { fallbackPrefix: 'APP' });
 * serviceLogger.i`Service started`;
 * // Output: "APP.UserService: Service started"
 *
 * // If applied to an already prefixed logger, fallback is ignored
 * const dbLogger = withPrefix(logger, 'DB');
 * const userDbLogger = withPrefix(dbLogger, 'UserService', {
 *   fallbackPrefix: 'APP', // This is ignored
 * });
 * userDbLogger.i`Service started`;
 * // Output: "DB.UserService: Service started"
 * ```
 *
 * @example Level Filtering
 *
 * ```ts
 * import { createConsoleLogLogger, withPrefix } from 'emitnlog/logger';
 *
 * // Underlying logger controls filtering
 * const base = createConsoleLogLogger('warning');
 * const dbLogger = withPrefix(base, 'DB');
 *
 * dbLogger.d`This debug message won't be logged`;
 * dbLogger.w`This warning will be logged`;
 * // Output: "DB: This warning will be logged"
 * ```
 *
 * **Tip:** When supported by your development environment, hovering over a prefixed logger variable shows the prefix in
 * the tooltip due to the type parameter, making it easier to identify which prefix is being used.
 *
 * @param logger The base logger to wrap with prefix functionality
 * @param prefix The prefix to prepend to all log messages
 * @param options Optional configuration for the logger behavior
 * @returns A new logger with the specified prefix, or the OFF_LOGGER if the input logger is OFF_LOGGER
 */
export const withPrefix = <
  TLogger extends Logger,
  const TPrefix extends string,
  const TSeparator extends string = '.',
  const TFallbackPrefix extends string | undefined = undefined,
>(
  logger: TLogger,
  prefix: TPrefix,
  options?: {
    /**
     * The separator to use between an existing prefix and the prefix passed to this method. Defaults to '.'.
     */
    readonly prefixSeparator?: TSeparator;
 
    /**
     * The separator to use between the prefix and the log message. Defaults to ': '.
     */
    readonly messageSeparator?: string;
 
    /**
     * The fallback prefix to use if the logger is not already a prefixed logger.
     */
    readonly fallbackPrefix?: TFallbackPrefix;
  },
): WithPrefixResult<TLogger, TPrefix, TSeparator, TFallbackPrefix> => {
  if (logger === OFF_LOGGER) {
    return OFF_LOGGER as unknown as WithPrefixResult<TLogger, TPrefix, TSeparator, TFallbackPrefix>;
  }
 
  let prefixSeparator: TSeparator;
  let messageSeparator: string;
 
  const data = inspectPrefixedLogger(logger);
  if (data) {
    logger = data.rootLogger as TLogger;
    prefixSeparator = data.separator as TSeparator;
    messageSeparator = data.messageSeparator;
    prefix = (prefix ? `${data.prefix}${prefixSeparator}${prefix}` : data.prefix) as TPrefix;
  } else {
    prefixSeparator = (options?.prefixSeparator ?? '.') as TSeparator;
    messageSeparator = options?.messageSeparator ?? ': ';
    if (options?.fallbackPrefix) {
      prefix = (prefix ? `${options.fallbackPrefix}${prefixSeparator}${prefix}` : options.fallbackPrefix) as TPrefix;
    }
  }
 
  const prefixedLogger = createPrefixedLogger(logger, prefix, prefixSeparator, messageSeparator);
  return prefixedLogger as unknown as WithPrefixResult<TLogger, TPrefix, TSeparator, TFallbackPrefix>;
};
 
type InternalPrefixedLogger<TPrefix extends string = string, TSeparator extends string = string> = PrefixedLogger<
  TPrefix,
  TSeparator
> & { readonly [messageSeparatorSymbol]: string; readonly [rootLoggerSymbol]: Logger };
 
const createPrefixedLogger = <TPrefix extends string = string, TSeparator extends string = string>(
  rootLogger: Logger,
  prefix: TPrefix,
  prefixSeparator: TSeparator,
  messageSeparator: string,
): PrefixedLogger<TPrefix, TSeparator> => {
  let pendingArgs: unknown[] = [];
 
  const consumePendingArgs = (): readonly unknown[] | undefined => {
    if (!pendingArgs.length) {
      return undefined;
    }
 
    const args = pendingArgs;
    pendingArgs = [];
    return args;
  };
 
  const runLogOperation = (internalLogger: InternalPrefixedLogger, operation: (logger: Logger) => void) => {
    const logger = internalLogger[rootLoggerSymbol];
    const currentArgs = consumePendingArgs();
    if (currentArgs) {
      logger.args(...currentArgs);
    }
    operation(logger);
  };
 
  const internalLogger: InternalPrefixedLogger<TPrefix, TSeparator> = {
    [prefixSymbol]: prefix,
    [separatorSymbol]: prefixSeparator,
    [messageSeparatorSymbol]: messageSeparator,
    [rootLoggerSymbol]: rootLogger,
 
    get level() {
      return internalLogger[rootLoggerSymbol].level;
    },
 
    args: (...args) => {
      pendingArgs.push(...args);
      return internalLogger;
    },
 
    trace: (message, ...args) => {
      runLogOperation(internalLogger, (logger) => logger.trace(toMessageProvider(internalLogger, message), ...args));
    },
    t: (strings, ...values) => {
      runLogOperation(internalLogger, (logger) => logger.t(toTemplateProvider(internalLogger, strings), ...values));
    },
 
    debug: (message, ...args) => {
      runLogOperation(internalLogger, (logger) => logger.debug(toMessageProvider(internalLogger, message), ...args));
    },
    d: (strings, ...values) => {
      runLogOperation(internalLogger, (logger) => logger.d(toTemplateProvider(internalLogger, strings), ...values));
    },
 
    info: (message, ...args) => {
      runLogOperation(internalLogger, (logger) => logger.info(toMessageProvider(internalLogger, message), ...args));
    },
    i: (strings, ...values) => {
      runLogOperation(internalLogger, (logger) => logger.i(toTemplateProvider(internalLogger, strings), ...values));
    },
 
    notice: (message, ...args) => {
      runLogOperation(internalLogger, (logger) => logger.notice(toMessageProvider(internalLogger, message), ...args));
    },
    n: (strings, ...values) => {
      runLogOperation(internalLogger, (logger) => logger.n(toTemplateProvider(internalLogger, strings), ...values));
    },
 
    warning: (input, ...args) => {
      runLogOperation(internalLogger, (logger) => {
        const converted = toErrorInput(internalLogger, input, args);
        logger.warning(converted.message, ...converted.args);
      });
    },
    w: (strings, ...values) => {
      runLogOperation(internalLogger, (logger) => logger.w(toTemplateProvider(internalLogger, strings), ...values));
    },
 
    error: (input, ...args) => {
      runLogOperation(internalLogger, (logger) => {
        const converted = toErrorInput(internalLogger, input, args);
        logger.error(converted.message, ...converted.args);
      });
    },
    e: (strings, ...values) => {
      runLogOperation(internalLogger, (logger) => logger.e(toTemplateProvider(internalLogger, strings), ...values));
    },
 
    critical: (input, ...args) => {
      runLogOperation(internalLogger, (logger) => {
        const converted = toErrorInput(internalLogger, input, args);
        logger.critical(converted.message, ...converted.args);
      });
    },
    c: (strings, ...values) => {
      runLogOperation(internalLogger, (logger) => logger.c(toTemplateProvider(internalLogger, strings), ...values));
    },
 
    alert: (input, ...args) => {
      runLogOperation(internalLogger, (logger) => {
        const converted = toErrorInput(internalLogger, input, args);
        logger.alert(converted.message, ...converted.args);
      });
    },
    a: (strings, ...values) => {
      runLogOperation(internalLogger, (logger) => logger.a(toTemplateProvider(internalLogger, strings), ...values));
    },
 
    emergency: (input, ...args) => {
      runLogOperation(internalLogger, (logger) => {
        const converted = toErrorInput(internalLogger, input, args);
        logger.emergency(converted.message, ...converted.args);
      });
    },
    em: (strings, ...values) => {
      runLogOperation(internalLogger, (logger) => logger.em(toTemplateProvider(internalLogger, strings), ...values));
    },
 
    log: (level, message, ...args) => {
      runLogOperation(internalLogger, (logger) =>
        logger.log(level, toMessageProvider(internalLogger, message), ...args),
      );
    },
 
    flush: rootLogger.flush ? () => internalLogger[rootLoggerSymbol].flush?.() : undefined,
    close: rootLogger.close ? () => internalLogger[rootLoggerSymbol].close?.() : undefined,
  } as const;
 
  return internalLogger;
};
 
const toMessageProvider = (prefixLogger: InternalPrefixedLogger, message: LogMessage) => (): string => {
  if (typeof message === 'function') {
    message = message();
  }
  return `${prefixLogger[prefixSymbol]}${prefixLogger[messageSeparatorSymbol]}${message}`;
};
 
const toErrorInput = (
  prefixLogger: InternalPrefixedLogger,
  input: LogMessage | Error | { error: unknown },
  args: readonly unknown[],
): { readonly message: LogMessage; readonly args: readonly unknown[] } => {
  const logger = prefixLogger[rootLoggerSymbol];
  const converted = BaseLogger.convertErrorInput(logger, input, args);
  return { message: toMessageProvider(prefixLogger, converted.message), args: converted.args };
};
 
const toTemplateProvider =
  (prefixLogger: InternalPrefixedLogger, strings: LogTemplateStringsArray) => (): TemplateStringsArray => {
    if (typeof strings === 'function') {
      strings = strings();
    }
 
    const prefix = `${prefixLogger[prefixSymbol]}${prefixLogger[messageSeparatorSymbol]}`;
    const newStrings = Array.from(strings);
    newStrings[0] = `${prefix}${newStrings[0]}`;
    const prefixedStrings = Object.assign(newStrings, { raw: Array.from(strings.raw) });
    prefixedStrings.raw[0] = `${prefix}${prefixedStrings.raw[0]}`;
 
    return prefixedStrings;
  };
 
/**
 * Appends a prefix to an existing prefixed logger, creating a hierarchical prefix structure.
 *
 * This utility function is specifically designed for use with already prefixed loggers. It extends the existing prefix
 * chain by appending a new prefix segment, using the same separator that was used in the original logger.
 *
 * Unlike `withPrefix`, this function has a simplified API that doesn't expose configuration options since it inherits
 * all settings (separators, etc.) from the existing prefixed logger.
 *
 * @example Basic Appending
 *
 * ```ts
 * import { createConsoleLogLogger, appendPrefix, withPrefix } from 'emitnlog/logger';
 *
 * const logger = createConsoleLogLogger('info');
 * const dbLogger = withPrefix(logger, 'DB');
 * const userDbLogger = appendPrefix(dbLogger, 'users');
 *
 * userDbLogger.i`User created successfully`;
 * // Output: "DB.users: User created successfully"
 * ```
 *
 * @example Multiple Levels of Nesting
 *
 * ```ts
 * import { appendPrefix, withPrefix } from 'emitnlog/logger';
 *
 * const serviceLogger = withPrefix(logger, 'UserService');
 * const repositoryLogger = appendPrefix(serviceLogger, 'Repository');
 * const cacheLogger = appendPrefix(repositoryLogger, 'Cache');
 *
 * cacheLogger.d`Cache hit for key: user_123`;
 * // Output: "UserService.Repository.Cache: Cache hit for key: user_123"
 * ```
 *
 * @example Preserving Custom Separators
 *
 * ```ts
 * // Original logger with custom separator
 * const apiLogger = withPrefix(logger, 'API', { prefixSeparator: '/' });
 * const v1Logger = appendPrefix(apiLogger, 'v1');
 * const usersLogger = appendPrefix(v1Logger, 'users');
 *
 * usersLogger.i`Processing user request`;
 * // Output: "API/v1/users: Processing user request"
 * ```
 *
 * @example Type Safety
 *
 * ```ts
 * import { appendPrefix, withPrefix } from 'emitnlog/logger';
 *
 * const dbLogger = withPrefix(logger, 'DB');
 * const userLogger = appendPrefix(dbLogger, 'User');
 * // Type of userLogger is PrefixedLogger<'DB.User', '.'>
 *
 * // TypeScript knows the exact prefix structure
 * const profileLogger = appendPrefix(userLogger, 'Profile');
 * // Type of profileLogger is PrefixedLogger<'DB.User.Profile', '.'>
 * ```
 *
 * @param logger The prefixed logger to append the prefix to
 * @param prefix The prefix segment to append to the existing prefix chain
 * @returns A new logger with the appended prefix, maintaining all original configuration
 */
export const appendPrefix = <
  const TCurrentPrefix extends string,
  const TSeparator extends string,
  const TLogger extends PrefixedLogger<TCurrentPrefix, TSeparator>,
  const TPrefix extends string,
>(
  logger: TLogger,
  prefix: TPrefix,
): WithPrefixResult<TLogger, TPrefix, TSeparator> => withPrefix(logger, prefix);
 
/**
 * Creates a prefixed logger with a completely new prefix, ignoring any existing prefix on the input logger.
 *
 * This utility function extracts the root (non-prefixed) logger from the input and applies a fresh prefix to it,
 * effectively "resetting" the prefix chain. This is useful when you want to create a new prefix hierarchy without
 * inheriting the existing prefix structure.
 *
 * Unlike `withPrefix`, which appends to existing prefixes, `resetPrefix` always starts with a clean slate.
 *
 * @example Basic Reset
 *
 * ```ts
 * import { createConsoleLogLogger, resetPrefix, withPrefix } from 'emitnlog/logger';
 *
 * const logger = createConsoleLogLogger('info');
 * const dbLogger = withPrefix(logger, 'DB');
 * const userDbLogger = withPrefix(dbLogger, 'users'); // Prefix: "DB.users"
 *
 * // Reset to a completely new prefix
 * const apiLogger = resetPrefix(userDbLogger, 'API'); // Prefix: "API" (not "DB.users.API")
 *
 * apiLogger.i`API server started`;
 * // Output: "API: API server started"
 * ```
 *
 * @example Switching Context
 *
 * ```ts
 * import { appendPrefix, resetPrefix, withPrefix } from 'emitnlog/logger';
 *
 * // Start with a deeply nested logger
 * const serviceLogger = withPrefix(logger, 'UserService');
 * const repoLogger = appendPrefix(serviceLogger, 'Repository');
 * const cacheLogger = appendPrefix(repoLogger, 'Cache'); // Prefix: "UserService.Repository.Cache"
 *
 * // Switch to a completely different context
 * const authLogger = resetPrefix(cacheLogger, 'Auth'); // Prefix: "Auth"
 * const tokenLogger = appendPrefix(authLogger, 'Token'); // Prefix: "Auth.Token"
 *
 * tokenLogger.d`Token validated successfully`;
 * // Output: "Auth.Token: Token validated successfully"
 * ```
 *
 * @example Custom Configuration
 *
 * ```ts
 * import { appendPrefix, resetPrefix, withPrefix } from 'emitnlog/logger';
 *
 * const existingLogger = withPrefix(logger, 'OldPrefix');
 *
 * // Reset with custom separators
 * const newLogger = resetPrefix(existingLogger, 'NewPrefix', { prefixSeparator: '/', messageSeparator: ' >> ' });
 *
 * const subLogger = appendPrefix(newLogger, 'SubModule');
 * subLogger.i`Module initialized`;
 * // Output: "NewPrefix/SubModule >> Module initialized"
 * ```
 *
 * @example Reusing Root Logger
 *
 * ```ts
 * import { appendPrefix, resetPrefix, withPrefix } from 'emitnlog/logger';
 *
 * // Multiple loggers sharing the same root but with different prefixes
 * const dbLogger = withPrefix(logger, 'DB');
 * const complexDbLogger = appendPrefix(dbLogger, 'Complex'); // Prefix: "DB.Complex"
 *
 * // Create parallel hierarchies from the same root
 * const cacheLogger = resetPrefix(complexDbLogger, 'Cache'); // Uses same root as dbLogger
 * const metricsLogger = resetPrefix(complexDbLogger, 'Metrics'); // Uses same root as dbLogger
 *
 * cacheLogger.i`Cache warmed up`; // Output: "Cache: Cache warmed up"
 * metricsLogger.i`Metrics collected`; // Output: "Metrics: Metrics collected"
 * ```
 *
 * @param logger The logger to extract the root logger from and apply a new prefix to
 * @param prefix The new prefix to apply (completely replacing any existing prefix)
 * @param options Optional configuration for the new prefixed logger
 * @returns A new logger with the specified prefix, using the root logger from the input
 */
export const resetPrefix = <const TPrefix extends string, const TSeparator extends string = '.'>(
  logger: Logger,
  prefix: TPrefix,
  options?: {
    /**
     * The separator to use between an existing prefix and the prefix passed to this method. Defaults to '.'.
     */
    readonly prefixSeparator?: TSeparator;
 
    /**
     * The separator to use between the prefix and the log message. Defaults to ': '.
     */
    readonly messageSeparator?: string;
  },
): WithPrefixResult<Logger, TPrefix, TSeparator> => {
  const data = inspectPrefixedLogger(logger);
  if (data) {
    logger = data.rootLogger;
  }
  return withPrefix(logger, prefix, options);
};
 
/**
 * Checks if a logger is a prefixed logger.
 *
 * @param logger The logger to check.
 * @returns True if the logger is a prefixed logger, false otherwise.
 */
export const isPrefixedLogger = (logger: Logger | undefined | null): logger is PrefixedLogger =>
  isNotNullable(logger) &&
  prefixSymbol in logger &&
  typeof logger[prefixSymbol] === 'string' &&
  separatorSymbol in logger &&
  typeof logger[separatorSymbol] === 'string' &&
  rootLoggerSymbol in logger &&
  logger[rootLoggerSymbol] !== undefined &&
  messageSeparatorSymbol in logger &&
  typeof logger[messageSeparatorSymbol] === 'string';
 
export type PrefixInformation = {
  readonly rootLogger: Logger;
  readonly prefix: string;
  readonly separator: string;
  readonly messageSeparator: string;
};
 
/**
 * Inspects a logger to get its prefix information.
 *
 * @param logger The logger to inspect.
 * @returns The prefix information, or undefined if the logger is not a prefixed logger.
 */
export const inspectPrefixedLogger = (logger: Logger): PrefixInformation | undefined =>
  isPrefixedLogger(logger)
    ? {
        rootLogger: (logger as InternalPrefixedLogger)[rootLoggerSymbol],
        prefix: logger[prefixSymbol]!,
        separator: logger[separatorSymbol]!,
        messageSeparator: (logger as InternalPrefixedLogger)[messageSeparatorSymbol],
      }
    : undefined;
 
/**
 * Important: this is an advanced utility, meant for logger implementors.
 *
 * Injects the prefix information from a source logger into a target logger so that the target is handled as a prefixed
 * logger by other utilities.
 *
 * Use it carefully:
 *
 * - This method modifies `target` so that object must not be read-only.
 * - This method does not cause `target` to write out the prefixed messages: this MUST be already handled by `target`
 *
 * @param source A prefixed logger
 * @param target A logger to inject the prefix information into
 * @returns The modified target logger, cast as the type
 */
export const injectPrefixInformation = <P extends PrefixedLogger>(source: P, target: Logger): P => {
  const prefixInformation = inspectPrefixedLogger(source);
  if (prefixInformation) {
    (target as unknown as Record<symbol, unknown>)[rootLoggerSymbol] = prefixInformation.rootLogger;
    (target as unknown as Record<symbol, unknown>)[prefixSymbol] = prefixInformation.prefix;
    (target as unknown as Record<symbol, unknown>)[separatorSymbol] = prefixInformation.separator;
    (target as unknown as Record<symbol, unknown>)[messageSeparatorSymbol] = prefixInformation.messageSeparator;
  }
 
  return target as unknown as P;
};
 
type WithPrefixResult<
  TLogger extends Logger,
  TNewPrefix extends string,
  TSeparator extends string = '.',
  TFallbackPrefix extends string | undefined = undefined,
> =
  TLogger extends PrefixedLogger<infer TPrevPrefix, infer TPrevSeparator>
    ? PrefixedLogger<`${TPrevPrefix}${TPrevSeparator}${TNewPrefix}`, TPrevSeparator>
    : TFallbackPrefix extends string
      ? TNewPrefix extends ''
        ? PrefixedLogger<`${TFallbackPrefix}`, TSeparator>
        : PrefixedLogger<`${TFallbackPrefix}${TSeparator}${TNewPrefix}`, TSeparator>
      : PrefixedLogger<TNewPrefix, TSeparator>;