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 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 230x 230x 2x 2x 45x 45x 45x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4658x 4658x 4654x 4654x 4654x 34x 34x 4654x 4658x 4624x 4624x 8x 8x 4624x 4616x 4658x 4658x 2x 1x 1x 1x 1x 1x 2x 191x 191x 2x 88x 88x 2x 591x 591x 2x 2x 2x 2x 3537x 3469x 3469x 68x 3537x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 564x 564x 2x 23x 23x 23x 23x 23x 2x 21x 21x 21x 2x 12x 12x 2x 880x 880x 880x 880x 2x 1173x 848x 848x 325x 325x 325x 325x 1173x 1173x 1173x 1173x 1173x 1173x 1173x 2x 1253x 1189x 1189x 5x 5x 5x 2x 2x 2x 2x 5x 1189x 1253x 1253x 2x 1219x 1219x 1219x 1219x 1219x 1219x 1219x 1129x 1129x 90x 90x 168x 21x 69x 1219x 1219x 1x 1x 1219x 2x 1219x 1219x 1219x 1219x 1219x 1219x 1219x 1219x 1173x 1219x 2x 749x 749x 2x 67x 67x 2x 184x 184x 2x 98x 98x 2x 59x 59x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 7x 7x 2x 5x 5x 2x 31x 31x 2x 1x 1x 2x 11x 11x 2x 1x 1x 2x 2x 1x 2x 2x 7x 7x 7x 7x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 4x 3x 3x 4x 2x 13x 13x 1x 1x 1x 12x 12x 13x 2x 1x 1x 2x 5x 1x 1x 1x 4x 4x 4x 4x 5x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 3x 2x 3x 3x 3x 2x 2x 3x 2x 2x 1x 1x | import { getContrastText, hexToRgba } from '@/theme/colors';
import { IS_DEV_BUILD } from '@/utils/isDevBuild';
/**
* Available logging levels in ascending order of severity:
* TRACE → DEBUG → INFO → WARN → ERROR → FATAL
*
* @category Utils
* @example
* ```typescript
* const logger = new Logger('App');
* logger.debug('This is a debug message');
* ```
* @source
*/
export enum LogLevel {
/** Finer-grained detail than debug, such as each step of a request or stream */
TRACE = 'trace',
/** Detailed information for debugging purposes */
DEBUG = 'debug',
/** General information about program execution */
INFO = 'info',
/** Potentially harmful situations that don't affect program execution */
WARN = 'warn',
/** Error conditions that affect program execution */
ERROR = 'error',
/** The app or a whole page can't continue, e.g. an uncaught exception or a crashed UI */
FATAL = 'fatal',
}
/**
* Every severity bucket a remote log sink can opt into, least to most severe.
* `Logger.info` and `Logger.log` both map to `'log'`.
* @category Utils
* @group Constants
* @example
* ```typescript
* REMOTE_LOG_LEVELS.includes('warn'); // true
* ```
* @source
*/
export const REMOTE_LOG_LEVELS = ['trace', 'debug', 'log', 'warn', 'error', 'fatal'] as const;
/**
* A severity bucket a remote log sink can opt into.
* @category Utils
* @group Types
* @example
* ```typescript
* const levels: RemoteLogLevel[] = ['log', 'warn', 'error'];
* ```
* @source
*/
export type RemoteLogLevel = (typeof REMOTE_LOG_LEVELS)[number];
/**
* Narrows an arbitrary value to a {@link RemoteLogLevel}.
* @category Utils
* @group Types
* @param value - The value to test
* @returns `true` if the value is one of the remote log levels
* @example
* ```typescript
* isRemoteLogLevel('warn'); // true
* isRemoteLogLevel('fatal'); // false
* ```
* @source
*/
export function isRemoteLogLevel(value: unknown): value is RemoteLogLevel {
return REMOTE_LOG_LEVELS.some((level) => level === value);
}
/**
* One log call as handed to a {@link RemoteLogSink}.
* - `level` - The remote severity bucket of the call.
* - `prefix` - The emitting logger's prefix (includes any `sub()` segments).
* - `message` - The message passed to the logger, before any formatting.
* - `args` - The extra arguments passed to the logger, unsanitized.
* - `location` - Where the call lives in the source, as `path:line#function`, when the build
* recorded it (see `tools/logCallSites.js`); otherwise `undefined`.
* - `context` - Key/value pairs describing what the app was doing when the call was made, such
* as the active search query (see {@link Logger.setContext}); `undefined` when there are none.
* @category Utils
* @group Types
* @example
* ```typescript
* const record: RemoteLogRecord = {
* level: 'warn',
* prefix: 'SupplierBase|fetch',
* message: 'Request failed',
* args: [new Error('timeout')],
* location: 'suppliers/SupplierBase.ts:1431#SupplierBase.fetch',
* };
* ```
* @source
*/
export interface RemoteLogRecord {
level: RemoteLogLevel;
prefix: string;
message: string;
args: readonly unknown[];
location?: string;
context?: Readonly<Record<string, string>>;
}
/**
* A destination that receives log calls in addition to the console, such as PostHog Logs.
* `isEnabled` is checked first so a disabled level costs no more than one function call.
* - `isEnabled` - Whether records at this level are currently wanted.
* - `emit` - Receives a record. Must not throw.
* @category Utils
* @group Types
* @example
* ```typescript
* const sink: RemoteLogSink = {
* isEnabled: (level) => level === 'error',
* emit: (record) => queue.push(record),
* };
* Logger.setRemoteSink(sink);
* ```
* @source
*/
export interface RemoteLogSink {
isEnabled(level: RemoteLogLevel): boolean;
emit(record: RemoteLogRecord): void;
}
/** Default log level when nothing is set via window/process env. DEBUG in dev, WARN in prod. */
const DEFAULT_LOG_LEVEL_FOR_BUILD: LogLevel = IS_DEV_BUILD ? LogLevel.DEBUG : LogLevel.WARN;
/** Separator inserted between a parent prefix and a child prefix in `Logger.sub()`. */
const SUB_LOGGER_SEPARATOR = '|';
/** Narrows an arbitrary string to a `LogLevel` enum member. */
function isLogLevel(value: string): value is LogLevel {
return (Object.values(LogLevel) as string[]).includes(value);
}
/**
* A flexible logging utility that supports different log levels and prefixed output.
*
* @remarks
* Works in both Node.js and browser environments. Each logger instance can either maintain
* its own fixed log level or automatically sync with environment variables. Instances of
* Logger should be mostly accurate substitutions for the console object as it includes
* all of the main methods of the console object, as well as some of the less commonly used
* methods methods (table, timer, group, etc).
*
* Features:
* - Environment-aware log level configuration (`process.env.LOG_LEVEL` or `window.LOG_LEVEL`)
* - Automatic environment variable monitoring (when using dynamic log levels)
* - Instance-specific log levels
* - Formatted output with timestamps
* - Support for additional metadata in logs
* - Can substitute for the console object
* @category Utils
* @summary
* A simple logger that works on both the commandline and in the browser, and can directly replace the console object (for most cases).
* @example
* ```typescript
* // Create a logger that automatically syncs with environment variables
* const envLogger = new Logger('App');
* // LOG_LEVEL=DEBUG
* envLogger.debug('Will show if LOG_LEVEL is DEBUG'); // Shows
* // LOG_LEVEL=INFO
* envLogger.debug('Will not show if LOG_LEVEL is INFO'); // Hidden
*
* // Create a logger with a fixed log level (ignores environment)
* const fixedLogger = new Logger('API', LogLevel.DEBUG);
* fixedLogger.debug('Always shows regardless of LOG_LEVEL');
*
* // Switch from environment sync to fixed level
* envLogger.setLogLevel(LogLevel.WARN); // Now ignores LOG_LEVEL changes
* ```
* @source
*/
export class Logger {
/**
* Maps log levels to their priority values for comparison.
* Higher numbers indicate higher priority levels.
* Used internally to determine if a message should be logged based on the current log level.
*
* Priority: TRACE=0, DEBUG=1, INFO=2, WARN=3, ERROR=4, FATAL=5
* @source
*/
private static readonly logLevelPriority: Record<LogLevel, number> = {
[LogLevel.TRACE]: 0,
[LogLevel.DEBUG]: 1,
[LogLevel.INFO]: 2,
[LogLevel.WARN]: 3,
[LogLevel.ERROR]: 4,
[LogLevel.FATAL]: 5,
};
/**
* Text color used for each level tag in colorized (browser) output.
* @source
*/
private static readonly levelColors: Record<LogLevel, string> = {
[LogLevel.TRACE]: '#b8bcc2',
[LogLevel.DEBUG]: '#9aa0a6',
[LogLevel.INFO]: '#4d7df2',
[LogLevel.WARN]: '#f5a623',
[LogLevel.ERROR]: '#e5484d',
[LogLevel.FATAL]: '#b3141b',
};
/**
* How each public level method maps to its internal level, its remote bucket, and the console
* method that prints it. `log` and `info` are both INFO and both send as the remote `log` level;
* `trace` prints through `console.debug` and `fatal` through `console.error`, since the console
* has no equivalents (and `console.trace` would add a stack to every call).
* @source
*/
private static readonly methodLevels: Record<
'trace' | 'debug' | 'info' | 'log' | 'warn' | 'error' | 'fatal',
{
level: LogLevel;
remote: RemoteLogLevel;
console: 'debug' | 'info' | 'log' | 'warn' | 'error';
}
> = {
trace: { level: LogLevel.TRACE, remote: 'trace', console: 'debug' },
debug: { level: LogLevel.DEBUG, remote: 'debug', console: 'debug' },
info: { level: LogLevel.INFO, remote: 'log', console: 'info' },
log: { level: LogLevel.INFO, remote: 'log', console: 'log' },
warn: { level: LogLevel.WARN, remote: 'warn', console: 'warn' },
error: { level: LogLevel.ERROR, remote: 'error', console: 'error' },
fatal: { level: LogLevel.FATAL, remote: 'fatal', console: 'error' },
};
/**
* Context shared by every logger (e.g. the active search query), merged into the record each
* remote log carries. Unset when nothing is in progress.
* @source
*/
private static globalContext?: Readonly<Record<string, string>>;
/**
* The registered remote sink, shared by every logger instance. Unset by default, in
* which case logging is console-only.
* @source
*/
private static remoteSink?: RemoteLogSink;
/**
* Stores named counters for the `count()` and `countReset()` methods.
* Keys are counter labels, values are the current count.
* @source
*/
private counters: Record<string, number> = {};
/**
* Context for this logger only, merged over the global context. Used where an object always
* belongs to one search (a supplier instance), so its late logs keep the right query.
* @source
*/
private context?: Readonly<Record<string, string>>;
/**
* Stores active timers for the `time()`, `timeEnd()`, and `timeLog()` methods.
* Keys are timer labels, values are the start timestamps in milliseconds.
* @source
*/
private timers: Record<string, number> = {};
/**
* Tracks the current nesting level for the `group()` and `groupCollapsed()` methods.
* Incremented by group/groupCollapsed, decremented by groupEnd.
* Used to determine the indentation level of log messages.
* @source
*/
private groupDepth = 0;
/**
* The indentation string used for each group level.
* Each nested group will add this string to the message prefix.
* Default is two spaces per level of nesting.
* @source
*/
private readonly groupIndent = ' ';
/**
* Retrieves the log level from environment variables.
* Checks the following in order:
* 1. `window.LOG_LEVEL` (Browser)
* 2. `process.env.LOG_LEVEL` (Node.js)
* 3. Falls back to the build-mode default — `DEBUG` in dev builds,
* `WARN` in production builds (see `DEFAULT_LOG_LEVEL_FOR_BUILD`).
*
* @example
* ```typescript
* // Dynamic logger that syncs with environment
* const appLogger = new Logger('App');
* appLogger.getEnvLogLevel(); // Returns LogLevel.DEBUG in dev, LogLevel.WARN in prod
* window.LOG_LEVEL = "DEBUG";
* appLogger.getEnvLogLevel(); // Returns LogLevel.DEBUG
* appLogger.debug("This will be logged");
* ```
*
* @returns The environment-specified log level, or the build-mode default if not set
* @source
*/
private static getEnvLogLevel(): LogLevel {
try {
// Check browser environment first
if (typeof window !== 'undefined') {
// Read the non-standard global without widening the Window type.
const windowLevel = Reflect.get(window, 'LOG_LEVEL');
const normalized = typeof windowLevel === 'string' ? windowLevel.toLowerCase() : undefined;
if (normalized && isLogLevel(normalized)) {
return normalized;
}
}
// Fall back to Node.js environment check
if (typeof process !== 'undefined' && process.env) {
const nodeLevel = process.env.LOG_LEVEL?.toLowerCase();
if (nodeLevel && isLogLevel(nodeLevel)) {
return nodeLevel;
}
}
return DEFAULT_LOG_LEVEL_FOR_BUILD;
} catch (err) {
// Log the error for debugging purposes but continue with default
console.warn('Error determining log level:', err);
return DEFAULT_LOG_LEVEL_FOR_BUILD;
}
}
public static setEnvLogLevel(level: LogLevel): void {
Reflect.set(window, 'LOG_LEVEL', level);
if (typeof process !== 'undefined' && process.env) {
process.env.LOG_LEVEL = level;
}
}
/**
* Registers (or clears) the sink that receives `debug`/`info`/`log`/`warn`/`error` calls
* from every logger instance, independent of the console log level.
*
* The sink is registered here rather than imported so `Logger` stays free of the
* analytics and storage modules that themselves create loggers.
* @param sink - The sink to register, or `undefined` to detach the current one
* @example
* ```typescript
* Logger.setRemoteSink({ isEnabled: () => true, emit: (record) => send(record) });
* new Logger('App').warn('Heads up'); // also reaches the sink as level 'warn'
* Logger.setRemoteSink(undefined);
* ```
* @source
*/
public static setRemoteSink(sink?: RemoteLogSink): void {
Logger.remoteSink = sink;
}
/**
* Sets (or clears) the context every logger attaches to its remote logs, such as the query of
* the search in progress. Console output is unchanged.
*
* @param context - Key/value pairs to attach, or `undefined` to clear
* @example
* ```typescript
* Logger.setContext({ search_query: 'acetone' });
* new Logger('Any').warn('Slow response'); // remote log carries search_query: 'acetone'
* Logger.setContext(undefined);
* ```
* @source
*/
public static setContext(context?: Readonly<Record<string, string>>): void {
Logger.globalContext = context;
}
/**
* Reads the current global context.
*
* @returns The context set by {@link Logger.setContext}, or `undefined` when none is set
* @example
* ```typescript
* Logger.setContext({ search_query: 'acetone' });
* Logger.getContext(); // { search_query: 'acetone' }
* ```
* @source
*/
public static getContext(): Readonly<Record<string, string>> | undefined {
return Logger.globalContext;
}
/**
* The identifier prefix that will be included in all log messages from this instance.
* Used to distinguish logs from different parts of the application.
* @source
*/
private prefix: string;
/**
* Optional hex color for this logger. When set, browser output is colorized
* with the prefix shown as a chip in this color; unset means plain output.
* @source
*/
private color?: string;
private _currentLogLevel: LogLevel;
/**
* The current minimum log level for this logger instance.
* Messages with a level lower than this will not be logged.
* Can be changed at runtime using `setLogLevel()`.
* @source
*/
private get currentLogLevel(): LogLevel {
if (this.useEnvOverride) {
return Logger.getEnvLogLevel();
}
return this._currentLogLevel;
}
/**
* Controls whether this logger instance should automatically sync its log level
* with environment variables. When true, the logger checks environment variables
* before each log operation to detect changes. When false, the logger maintains
* a fixed log level regardless of environment changes.
* @source
*/
private useEnvOverride: boolean;
/**
* Creates a new Logger instance with the specified prefix and optional initial log level.
*
* @param prefix - A string that will be included in all log messages for this instance
* @param initialLogLevel - Optional log level to set at initialization. If provided,
* the logger will use this fixed level and ignore environment
* variables. If not provided, the logger will automatically
* sync with environment variables (`process.env.LOG_LEVEL` or
* `window.LOG_LEVEL`) and update its level when they change.
* @param color - Optional hex color (e.g. `"#fa938e"`). When set, browser output is
* colorized with the prefix rendered as a chip in this color.
*
* @example
* ```typescript
* // Dynamic logger that syncs with environment
* const appLogger = new Logger('App');
*
* // Fixed level loggers that ignore environment
* const debugLogger = new Logger('API', LogLevel.DEBUG);
* const errorLogger = new Logger('DB', LogLevel.ERROR);
*
* // Colorized logger (prefix shown as a colored chip in the browser console)
* const supplierLogger = new Logger('SupplierAmbeed', undefined, '#4db6ac');
* ```
* @source
*/
constructor(prefix: string, initialLogLevel?: LogLevel, color?: string) {
this.prefix = prefix;
this.color = color;
this.useEnvOverride = !initialLogLevel;
this._currentLogLevel = initialLogLevel ?? this.currentLogLevel;
}
/**
* Sets (or clears) the color used to colorize this logger's browser output.
*
* @param color - A hex color string, or undefined to disable colorization
*
* @example
* ```typescript
* const logger = new Logger('SupplierAmbeed');
* logger.setColor('#4db6ac'); // prefix now rendered as a teal chip
* ```
* @source
*/
public setColor(color?: string): void {
this.color = color;
}
/**
* Sets (or clears) context attached to this logger's remote logs only. It is merged over, and
* wins against, the global context from {@link Logger.setContext}.
*
* @param context - Key/value pairs to attach, or `undefined` to clear
* @example
* ```typescript
* const logger = new Logger('SupplierBase');
* logger.setContext({ search_query: 'acetone' });
* ```
* @source
*/
public setContext(context?: Readonly<Record<string, string>>): void {
this.context = context;
}
/**
* Creates a child logger whose prefix is this logger's prefix with `suffix`
* appended after a `|` separator. Useful for scoping log lines to a specific
* operation without reconstructing a logger or restating the log level.
*
* The child is a new, independent instance (its own counters/timers/groups) that
* inherits this logger's level configuration: an env-synced parent yields an
* env-synced child, and a fixed-level parent seeds the child with that same level.
* Because `sub()` returns a `Logger`, calls chain to any depth.
* @param suffix - The prefix segment to append for the child logger
* @returns A new `Logger` whose prefix is the parent prefix, a `|`, then `suffix`
* @example
* ```typescript
* const logger = new Logger('SupplierBase');
* const l = logger.sub('httpPostFormData');
* l.log('Hello');
* // [2024-01-01T00:00:00.000Z] [INFO] [SupplierBase|httpPostFormData] Hello
*
* logger.sub('a').sub('b').sub('c').info('x');
* // [2024-01-01T00:00:00.000Z] [INFO] [SupplierBase|a|b|c] x
* ```
* @source
*/
public sub(suffix: string): Logger {
return new Logger(
`${this.prefix}${SUB_LOGGER_SEPARATOR}${suffix}`,
this.useEnvOverride ? undefined : this._currentLogLevel,
this.color,
);
}
/**
* Sets a fixed minimum log level for this logger instance. This disables automatic
* environment variable syncing - the logger will maintain this level regardless
* of environment changes until `setLogLevel` is called again.
*
* @param level - The new minimum log level to fix this logger instance at
*
* @example
* ```typescript
* const logger = new Logger('App'); // Initially syncs with environment
* logger.setLogLevel(LogLevel.WARN); // Now fixed at WARN, ignores environment
* ```
* @source
*/
public setLogLevel(level: LogLevel): void {
this.useEnvOverride = false;
this._currentLogLevel = level;
}
/**
* Gets the current minimum log level for this logger instance.
* Note that if this logger is syncing with environment variables,
* this value may change between calls as the environment changes.
*
* @returns The current log level
*
* @example
* ```typescript
* const logger = new Logger('MyApp', LogLevel.WARN);
* logger.getLogLevel(); // Returns: LogLevel.WARN
*
* // With environment sync
* const envLogger = new Logger('MyApp');
* envLogger.getLogLevel(); // Returns: LogLevel.INFO (default)
*
* window.LOG_LEVEL = 'DEBUG';
* envLogger.debug('trigger check');
* envLogger.getLogLevel(); // Returns: LogLevel.DEBUG
*
* // After setting fixed level
* envLogger.setLogLevel(LogLevel.ERROR);
* envLogger.getLogLevel(); // Returns: LogLevel.ERROR (now fixed)
* ```
* @source
*/
public getLogLevel(): LogLevel {
return this.currentLogLevel;
}
/**
* Formats a log message with timestamp, level, and prefix.
*
* @param level - The log level for the message
* @param message - The message to format
* @returns The formatted message string
*
* @example
* ```typescript
* // Internal method usage:
* this.formatMessage(LogLevel.INFO, "User logged in");
* // Returns: "[2024-01-01T00:00:00.000Z] [INFO] [MyApp] User logged in"
*
* this.formatMessage(LogLevel.ERROR, "Database connection failed");
* // Returns: "[2024-01-01T00:00:00.000Z] [ERROR] [MyApp] Database connection failed"
* ```
* @source
*/
private formatMessage(level: LogLevel, message: string): string {
const timestamp = new Date().toISOString();
const indentation = this.groupIndent.repeat(this.groupDepth);
return `[${timestamp}] [${level.toUpperCase()}] [${this.prefix}] ${indentation}${message}`;
}
/**
* Builds the argument list to spread into a `console` call. For uncolored loggers
* (or non-browser consoles that would print `%c` literally) this is the single
* plain string from `formatMessage`. When a color is set in a browser, it returns
* a `%c` format string plus the CSS style arguments: a muted timestamp carrying a
* thick left border in the level's color, the prefix as a chip in the logger's
* color (dimmed a step per `sub()` depth), and a reset for the message.
*
* @param level - The log level for the message
* @param message - The message to format
* @returns The arguments to spread into `console.log`/`info`/etc.
*
* @example
* ```typescript
* // Uncolored: ["[2024-01-01T00:00:00.000Z] [INFO] [MyApp] hi"]
* // Colored: ["%c... %cMyApp%c hi", "border-left:5px solid #4d7df2; ...", ...styles]
* console.info(...this.formatArgs(LogLevel.INFO, "hi"));
* ```
* @source
*/
private formatArgs(level: LogLevel, message: string): unknown[] {
if (this.color === undefined || typeof window === 'undefined') {
return [this.formatMessage(level, message)];
}
// Short local time reads better than a full ISO string in a live devtools console.
const timestamp = new Date().toLocaleTimeString();
const indentation = this.groupIndent.repeat(this.groupDepth);
// Each sub() adds a `|` segment; dim the chip a step per level of nesting.
const subDepth = this.prefix.split(SUB_LOGGER_SEPARATOR).length - 1;
const chipAlpha = Math.max(0.4, Math.round((1 - subDepth * 0.12) * 100) / 100);
const chipBackground = subDepth <= 0 ? this.color : hexToRgba(this.color, chipAlpha);
return [
`%c${timestamp} %c${this.prefix}%c ${indentation}${message}`,
`border-left:5px solid ${Logger.levelColors[level]}; padding-left:8px; color:#6b7280;`,
`background:${chipBackground}; color:${getContrastText(this.color)}; padding:1px 6px; border-radius:4px; font-weight:600;`,
'color:inherit; background:transparent; font-weight:normal; padding:0;',
];
}
/**
* Determines if a message at the given level should be logged based on the current log level.
* If environment syncing is enabled, checks for environment changes before making the determination.
*
* @param messageLevel - The level of the message being logged
* @returns true if the message should be logged, false otherwise
*
* @example
* ```typescript
* // Internal method usage:
* const logger = new Logger('MyApp', LogLevel.INFO);
*
* logger.shouldLog(LogLevel.DEBUG); // Returns: false
* logger.shouldLog(LogLevel.INFO); // Returns: true
* logger.shouldLog(LogLevel.WARN); // Returns: true
* logger.shouldLog(LogLevel.ERROR); // Returns: true
*
* // With environment sync:
* const envLogger = new Logger('MyApp');
* window.LOG_LEVEL = 'DEBUG';
* envLogger.shouldLog(LogLevel.DEBUG); // Updates level and returns true
* ```
* @source
*/
private shouldLog(messageLevel: LogLevel): boolean {
// If using environment override, check for changes
if (this.useEnvOverride) {
const envLevel = Logger.getEnvLogLevel();
if (envLevel !== this._currentLogLevel) {
const oldLevel = this._currentLogLevel;
this._currentLogLevel = envLevel;
// Only log the level change if it would be visible at the new level
if (Logger.logLevelPriority[LogLevel.INFO] >= Logger.logLevelPriority[envLevel]) {
console.info(
this.formatMessage(
LogLevel.INFO,
`Log level changed from ${oldLevel.toUpperCase()} to ${envLevel.toUpperCase().toUpperCase()} due to environment update`,
),
);
}
}
}
return Logger.logLevelPriority[messageLevel] >= Logger.logLevelPriority[this.currentLogLevel];
}
/**
* Hands a log call to the registered remote sink, if it wants this level. Runs before the
* console gate, so the sink's levels are independent of the console log level.
*
* @param level - The remote severity bucket of the call
* @param message - The message passed to the logger
* @param args - The extra arguments passed to the logger
* @param location - Where the call lives in the source (`path:line#function`), if known
* @example
* ```typescript
* this.forwardRemote('warn', 'Request failed', [error], 'suppliers/Foo.ts:12#Foo.fetch');
* ```
* @source
*/
private forwardRemote(
level: RemoteLogLevel,
message: string,
args: readonly unknown[],
location?: string,
): void {
const sink = Logger.remoteSink;
if (sink === undefined || !sink.isEnabled(level)) {
return;
}
try {
const context =
Logger.globalContext || this.context
? { ...Logger.globalContext, ...this.context }
: undefined;
sink.emit({ level, prefix: this.prefix, message, args, location, context });
} catch (err) {
// A broken sink must never break the caller's logging.
console.debug('Remote log sink failed:', err);
}
}
/**
* Shared body of every level method: hands the call to the remote sink (independent of the
* console level), then writes it to the console if the logger's level allows.
*
* @param method - The public level method that was called
* @param location - Where the call lives in the source (`path:line#function`), if known
* @param message - The message passed to the logger
* @param args - The extra arguments passed to the logger
* @example
* ```typescript
* this.write('warn', undefined, 'Request failed', [error]);
* ```
* @source
*/
private write(
method: keyof typeof Logger.methodLevels,
location: string | undefined,
message: string,
args: readonly unknown[],
): void {
const { level, remote, console: consoleMethod } = Logger.methodLevels[method];
this.forwardRemote(remote, message, args, location);
if (!this.shouldLog(level)) return;
console[consoleMethod](...this.formatArgs(level, message), ...args);
}
/**
* Logs a debug message if the current log level is `DEBUG` or lower.
* If environment syncing is enabled, checks environment variables before logging.
*
* @param message - The message to log
* @param args - Additional arguments to pass to `console.debug`
*
* @example
* ```typescript
* const logger = new Logger('App', LogLevel.DEBUG);
* logger.debug('Processing payload', { userId: 123, action: 'login' });
* // [2024-03-19T10:30:15.123Z] [DEBUG] [App] Processing payload { userId: 123, action: 'login' }
* ```
* @source
*/
public debug(message: string, ...args: unknown[]): void {
this.write('debug', undefined, message, args);
}
/**
* Logs an info message if the current log level is `INFO` or lower.
* If environment syncing is enabled, checks environment variables before logging.
*
* @param message - The message to log
* @param args - Additional arguments to pass to `console.info`
*
* @example
* ```typescript
* const logger = new Logger('App', LogLevel.INFO);
* logger.info('User logged in', { userId: 123 });
* // [2024-03-19T10:30:15.124Z] [INFO] [App] User logged in { userId: 123 }
* ```
* @source
*/
public info(message: string, ...args: unknown[]): void {
this.write('info', undefined, message, args);
}
/**
* Logs a warning message if the current log level is `WARN` or lower.
* If environment syncing is enabled, checks environment variables before logging.
*
* @param message - The message to log
* @param args - Additional arguments to pass to `console.warn`
*
* @example
* ```typescript
* const logger = new Logger('App', LogLevel.WARN);
* logger.warn('High memory usage', { memoryUsed: '85%' });
* // [2024-03-19T10:30:15.125Z] [WARN] [App] High memory usage { memoryUsed: '85%' }
* ```
* @source
*/
public warn(message: string, ...args: unknown[]): void {
this.write('warn', undefined, message, args);
}
/**
* Logs an error message if the current log level is `ERROR` or lower.
* If environment syncing is enabled, checks environment variables before logging.
*
* @param message - The message to log
* @param args - Additional arguments to pass to `console.error`
*
* @example
* ```typescript
* const logger = new Logger('MyApp');
*
* // Basic error
* logger.error('Failed to connect to database');
* // Output: [2024-01-01T00:00:00.000Z] [ERROR] [MyApp] Failed to connect to database
*
* // Convention: put the cause in the message and pass details as one object, with the
* // caught error under the `error` key (remote logs read the stack from it)
* try {
* throw new Error('Connection timeout');
* } catch (error) {
* logger.error(`Database error: ${getErrorMessage(error)}`, { error });
* // Output: [2024-01-01T00:00:00.000Z] [ERROR] [MyApp] Database error: Connection timeout { error: ... }
* }
*
* // More details go in the same object
* logger.error('Operation failed', { code: 500, reason: 'Timeout', endpoint: '/api/data' });
* ```
* @source
*/
public error(message: string, ...args: unknown[]): void {
this.write('error', undefined, message, args);
}
/**
* General purpose logging method. Uses `INFO` level.
* If environment syncing is enabled, checks environment variables before logging.
*
* @param message - The message to log
* @param args - Additional arguments to pass to `console.log`
*
* @example
* ```typescript
* const logger = new Logger('MyApp');
*
* // Basic logging
* logger.log('Application started');
* // Output: [2024-01-01T00:00:00.000Z] [INFO] [MyApp] Application started
*
* // Logging with additional data
* logger.log('User settings', { theme: 'dark', notifications: true });
* // Output: [2024-01-01T00:00:00.000Z] [INFO] [MyApp] User settings { theme: 'dark', notifications: true }
*
* // Multiple arguments
* logger.log('Process completed', 'Duration:', 1234, 'ms');
* // Output: [2024-01-01T00:00:00.000Z] [INFO] [MyApp] Process completed Duration: 1234 ms
* ```
* @source
*/
public log(message: string, ...args: unknown[]): void {
this.write('log', undefined, message, args);
}
/**
* Logs a debug message with its source location. Identical to `debug()` except the first argument is the call's source location.
* The build rewrites `logger.debug(...)` calls to this form (see `tools/logCallSites.js`) so
* remote logs can report the file, line and function; write plain `debug()` in source.
*
* @param location - Where the call lives, as `path:line#function`
* @param message - The message to log
* @param args - Additional arguments
* @example
* ```typescript
* logger.debugAt('suppliers/Foo.ts:12#Foo.fetch', 'Request failed', { status: 503 });
* ```
* @source
*/
public debugAt(location: string, message: string, ...args: unknown[]): void {
this.write('debug', location, message, args);
}
/**
* Logs an info message with its source location. Identical to `info()` except the first argument is the call's source location.
* The build rewrites `logger.info(...)` calls to this form (see `tools/logCallSites.js`) so
* remote logs can report the file, line and function; write plain `info()` in source.
*
* @param location - Where the call lives, as `path:line#function`
* @param message - The message to log
* @param args - Additional arguments
* @example
* ```typescript
* logger.infoAt('suppliers/Foo.ts:12#Foo.fetch', 'Request failed', { status: 503 });
* ```
* @source
*/
public infoAt(location: string, message: string, ...args: unknown[]): void {
this.write('info', location, message, args);
}
/**
* Logs a general message (INFO level) with its source location. Identical to `log()` except the first argument is the call's source location.
* The build rewrites `logger.log(...)` calls to this form (see `tools/logCallSites.js`) so
* remote logs can report the file, line and function; write plain `log()` in source.
*
* @param location - Where the call lives, as `path:line#function`
* @param message - The message to log
* @param args - Additional arguments
* @example
* ```typescript
* logger.logAt('suppliers/Foo.ts:12#Foo.fetch', 'Request failed', { status: 503 });
* ```
* @source
*/
public logAt(location: string, message: string, ...args: unknown[]): void {
this.write('log', location, message, args);
}
/**
* Logs a warning with its source location. Identical to `warn()` except the first argument is the call's source location.
* The build rewrites `logger.warn(...)` calls to this form (see `tools/logCallSites.js`) so
* remote logs can report the file, line and function; write plain `warn()` in source.
*
* @param location - Where the call lives, as `path:line#function`
* @param message - The message to log
* @param args - Additional arguments
* @example
* ```typescript
* logger.warnAt('suppliers/Foo.ts:12#Foo.fetch', 'Request failed', { status: 503 });
* ```
* @source
*/
public warnAt(location: string, message: string, ...args: unknown[]): void {
this.write('warn', location, message, args);
}
/**
* Logs an error with its source location. Identical to `error()` except the first argument is the call's source location.
* The build rewrites `logger.error(...)` calls to this form (see `tools/logCallSites.js`) so
* remote logs can report the file, line and function; write plain `error()` in source.
*
* @param location - Where the call lives, as `path:line#function`
* @param message - The message to log
* @param args - Additional arguments
* @example
* ```typescript
* logger.errorAt('suppliers/Foo.ts:12#Foo.fetch', 'Request failed', { status: 503 });
* ```
* @source
*/
public errorAt(location: string, message: string, ...args: unknown[]): void {
this.write('error', location, message, args);
}
/**
* Logs a trace message: very fine-grained detail, such as each step of a request. Hidden from the console unless the level is `TRACE`, and sent remotely only when `trace` is selected.
*
* @param message - The message to log
* @param args - Additional details, passed as one object
* @example
* ```typescript
* logger.trace('Received product from stream', { detail: 1 });
* ```
* @source
*/
public trace(message: string, ...args: unknown[]): void {
this.write('trace', undefined, message, args);
}
/**
* Logs a trace message: very fine-grained detail, such as each step of a request. Hidden from the console unless the level is `TRACE`, and sent remotely only when `trace` is selected with its source location. Identical to `trace()` except the first
* argument is the call's location; the build rewrites `logger.trace(...)` to this form, so
* write plain `trace()` in source.
*
* @param location - Where the call lives, as `path:line#function`
* @param message - The message to log
* @param args - Additional details
* @example
* ```typescript
* logger.traceAt('suppliers/Foo.ts:12#Foo.fetch', 'Received product from stream', { detail: 1 });
* ```
* @source
*/
public traceAt(location: string, message: string, ...args: unknown[]): void {
this.write('trace', location, message, args);
}
/**
* Logs a fatal error: the app or a whole page cannot continue, such as an uncaught exception or a crashed UI. Always shown in the console.
*
* @param message - The message to log
* @param args - Additional details, passed as one object
* @example
* ```typescript
* logger.fatal('Uncaught exception', { detail: 1 });
* ```
* @source
*/
public fatal(message: string, ...args: unknown[]): void {
this.write('fatal', undefined, message, args);
}
/**
* Logs a fatal error: the app or a whole page cannot continue, such as an uncaught exception or a crashed UI. Always shown in the console with its source location. Identical to `fatal()` except the first
* argument is the call's location; the build rewrites `logger.fatal(...)` to this form, so
* write plain `fatal()` in source.
*
* @param location - Where the call lives, as `path:line#function`
* @param message - The message to log
* @param args - Additional details
* @example
* ```typescript
* logger.fatalAt('suppliers/Foo.ts:12#Foo.fetch', 'Uncaught exception', { detail: 1 });
* ```
* @source
*/
public fatalAt(location: string, message: string, ...args: unknown[]): void {
this.write('fatal', location, message, args);
}
/**
* Displays an interactive listing of the properties of an object.
* Uses DEBUG level.
*
* @param item - The object to inspect
* @param options - Optional `console.dir` options
*
* @example
* ```typescript
* const logger = new Logger('MyApp', LogLevel.DEBUG);
*
* // Basic object inspection
* const user = { id: 1, name: 'John', settings: { theme: 'dark' } };
* logger.dir(user);
*
* // With custom options
* logger.dir(user, { depth: 1, colors: true });
*
* // Complex object
* const response = await fetch('/api/data');
* const data = await response.json();
* logger.dir(data, { depth: null }); // Show all levels
* ```
* @source
*/
public dir(item: unknown, options?: { depth?: number; colors?: boolean }): void {
if (!this.shouldLog(LogLevel.DEBUG)) return;
console.dir(item, options);
}
/**
* Logs the number of times this method has been called with a given label.
* Uses `INFO` level.
*
* @param label - The counter label
*
* @example
* ```typescript
* const logger = new Logger('MyApp');
*
* // Count API calls
* logger.count('api-requests');
* // Output: [2024-01-01T00:00:00.000Z] [INFO] [MyApp] api-requests: 1
*
* logger.count('api-requests');
* // Output: [2024-01-01T00:00:00.000Z] [INFO] [MyApp] api-requests: 2
*
* // Using default label
* logger.count();
* // Output: [2024-01-01T00:00:00.000Z] [INFO] [MyApp] default: 1
*
* // Multiple counters
* logger.count('errors');
* logger.count('api-requests');
* // Output: [2024-01-01T00:00:00.000Z] [INFO] [MyApp] errors: 1
* // Output: [2024-01-01T00:00:00.000Z] [INFO] [MyApp] api-requests: 3
* ```
* @source
*/
public count(label = 'default'): void {
if (!this.shouldLog(LogLevel.INFO)) return;
this.counters[label] = (this.counters[label] || 0) + 1;
console.log(this.formatMessage(LogLevel.INFO, `${label}: ${this.counters[label]}`));
}
/**
* Resets the counter for a given label.
*
* @param label - The counter label to reset
*
* @example
* ```typescript
* const logger = new Logger('MyApp');
*
* // Count and reset
* logger.count('api-requests'); // Output: api-requests: 1
* logger.count('api-requests'); // Output: api-requests: 2
* logger.countReset('api-requests');
* logger.count('api-requests'); // Output: api-requests: 1
*
* // Reset default counter
* logger.count(); // Output: default: 1
* logger.countReset();
* logger.count(); // Output: default: 1
*
* // Reset non-existent counter (silent operation)
* logger.countReset('unknown');
* ```
* @source
*/
public countReset(label = 'default'): void {
delete this.counters[label];
}
/**
* Creates a new inline group in the console output.
* Subsequent console messages will be indented.
* Uses `INFO` level.
*
* @param label - The group label
*
* @example
* ```typescript
* const logger = new Logger('MyApp');
*
* // Basic grouping
* logger.group('User Authentication');
* logger.log('Checking credentials...');
* logger.log('User authenticated');
* logger.groupEnd();
*
* // Nested groups
* logger.group('API Response');
* logger.log('Status: 200');
* logger.group('Response Body');
* logger.log('Data loaded');
* logger.groupEnd();
* logger.log('Request completed');
* logger.groupEnd();
*
* // Group without label
* logger.group();
* logger.log('Grouped message');
* logger.groupEnd();
* ```
* @source
*/
public group(label?: string): void {
if (!this.shouldLog(LogLevel.INFO)) return;
if (label) {
console.log(this.formatMessage(LogLevel.INFO, label));
}
this.groupDepth++;
}
/**
* Creates a new inline group in the console output, but starts collapsed.
* Subsequent console messages will be indented.
* Uses `INFO` level.
*
* @param label - The group label
*
* @example
* ```typescript
* const logger = new Logger('MyApp');
*
* // Collapsed debug information
* logger.groupCollapsed('Debug Details');
* logger.log('Environment:', process.env.NODE_ENV);
* logger.log('Platform:', process.platform);
* logger.log('Memory Usage:', process.memoryUsage());
* logger.groupEnd();
*
* // Nested collapsed groups
* logger.groupCollapsed('Request Details');
* logger.log('URL:', request.url);
* logger.groupCollapsed('Headers');
* logger.log(request.headers);
* logger.groupEnd();
* logger.log('Body:', request.body);
* logger.groupEnd();
* ```
* @source
*/
public groupCollapsed(label?: string): void {
if (!this.shouldLog(LogLevel.INFO)) return;
if (label) {
console.log(this.formatMessage(LogLevel.INFO, label));
}
this.groupDepth++;
}
/**
* Exits the current inline group in the console.
* @source
*/
public groupEnd(): void {
if (this.groupDepth > 0) {
this.groupDepth--;
}
}
/**
* Displays tabular data as a table.
* Uses `INFO` level.
*
* @param tabularData - Data to display in table format
* @param properties - Optional array of property names to display
*
* @example
* ```typescript
* const logger = new Logger('MyApp');
*
* // Simple array of objects
* const users = [
* { id: 1, name: 'John', role: 'admin' },
* { id: 2, name: 'Jane', role: 'user' }
* ];
* logger.table(users);
*
* // Specify columns to display
* logger.table(users, ['name', 'role']);
*
* // Array of arrays
* const matrix = [
* [1, 2, 3],
* [4, 5, 6]
* ];
* logger.table(matrix);
*
* // Object with nested data
* const data = {
* users: { count: 2, active: 1 },
* posts: { count: 10, draft: 3 }
* };
* logger.table(data);
* ```
* @source
*/
public table(tabularData: unknown, properties?: readonly string[]): void {
if (!this.shouldLog(LogLevel.INFO)) return;
if (typeof tabularData !== 'object' || tabularData === null) {
console.log(this.formatMessage(LogLevel.INFO, 'Invalid data for table display'));
return;
}
console.log(this.formatMessage(LogLevel.INFO, 'Table Output:'));
console.table(tabularData, properties);
}
/**
* Clears the console if possible.
* @source
*/
public clear(): void {
console.clear();
}
/**
* Creates a new timing with the specified label.
* Uses `DEBUG` level for output.
*
* @param label - The timer label
*
* @example
* ```typescript
* const logger = new Logger('Performance');
*
* // Start a named timer
* logger.time('database-query');
* // Output: [2024-01-01T00:00:00.000Z] [DEBUG] [Performance] Timer 'database-query' started
*
* // Start default timer
* logger.time();
* // Output: [2024-01-01T00:00:00.000Z] [DEBUG] [Performance] Timer 'default' started
*
* // Attempting to start an existing timer
* logger.time('database-query');
* // Output: [2024-01-01T00:00:00.000Z] [WARN] [Performance] Timer 'database-query' already exists
* ```
* @source
*/
public time(label = 'default'): void {
if (this.timers[label]) {
this.warn(`Timer '${label}' already exists`);
return;
}
this.timers[label] = performance.now();
if (this.shouldLog(LogLevel.DEBUG)) {
console.debug(this.formatMessage(LogLevel.DEBUG, `Timer '${label}' started`));
}
}
/**
* Stops a timer and logs the elapsed time.
* Uses `DEBUG` level for output.
*
* @param label - The timer label
*
* @example
* ```typescript
* const logger = new Logger('Performance');
*
* // Basic timer usage
* logger.time('operation');
* await someAsyncOperation();
* logger.timeEnd('operation');
* // Output: [2024-01-01T00:00:00.000Z] [DEBUG] [Performance] Timer 'operation': 1234.56ms
*
* // Attempting to end non-existent timer
* logger.timeEnd('invalid-timer');
* // Output: [2024-01-01T00:00:00.000Z] [WARN] [Performance] Timer 'invalid-timer' does not exist
*
* // Using default timer
* logger.time();
* await someAsyncOperation();
* logger.timeEnd();
* // Output: [2024-01-01T00:00:00.000Z] [DEBUG] [Performance] Timer 'default': 1234.56ms
* ```
* @source
*/
public timeEnd(label = 'default'): void {
if (!this.timers[label]) {
this.warn(`Timer '${label}' does not exist`);
return;
}
const duration = performance.now() - this.timers[label];
delete this.timers[label];
if (this.shouldLog(LogLevel.DEBUG)) {
console.debug(
this.formatMessage(LogLevel.DEBUG, `Timer '${label}': ${duration.toFixed(2)}ms`),
);
}
}
/**
* Logs the current value of a timer without stopping it.
* Uses `DEBUG` level for output.
*
* @param label - The timer label
* @param args - Additional data to log with the timer
*
* @example
* ```typescript
* const logger = new Logger('Performance');
*
* // Log progress during a long operation
* logger.time('long-task');
*
* for (const item of items) {
* await processItem(item);
* logger.timeLog('long-task', { processedItem: item.id });
* // Output: [2024-01-01T00:00:00.000Z] [DEBUG] [Performance] Timer 'long-task': 1234.56ms { processedItem: 123 }
* }
*
* logger.timeEnd('long-task');
*
* // Attempting to log non-existent timer
* logger.timeLog('invalid-timer');
* // Output: [2024-01-01T00:00:00.000Z] [WARN] [Performance] Timer 'invalid-timer' does not exist
* ```
* @source
*/
public timeLog(label = 'default', ...args: unknown[]): void {
if (!this.timers[label]) {
this.warn(`Timer '${label}' does not exist`);
return;
}
const duration = performance.now() - this.timers[label];
if (this.shouldLog(LogLevel.DEBUG)) {
console.debug(
this.formatMessage(LogLevel.DEBUG, `Timer '${label}': ${duration.toFixed(2)}ms`),
...args,
);
}
}
/**
* Adds a timestamp marker to the timeline in browser devtools.
* In non-browser environments, logs a timestamp message.
* Uses DEBUG level.
*
* @param label - Optional label for the timestamp
*
* @example
* ```typescript
* const logger = new Logger('Timeline');
*
* // Add labeled timestamp
* logger.timeStamp('User Clicked Button');
* // In Browser DevTools: Adds timeline marker 'User Clicked Button'
* // In Console: [2024-01-01T00:00:00.000Z] [DEBUG] [Timeline] Timestamp 'User Clicked Button': 2024-01-01T00:00:00.000Z
*
* // Add unlabeled timestamp
* logger.timeStamp();
* // In Browser DevTools: Adds timeline marker
* // In Console: [2024-01-01T00:00:00.000Z] [DEBUG] [Timeline] Timestamp: 2024-01-01T00:00:00.000Z
*
* // Useful for marking significant events in application flow
* async function handleUserAction() {
* logger.timeStamp('Action Started');
* await processAction();
* logger.timeStamp('Action Completed');
* }
* ```
* @source
*/
public timeStamp(label?: string): void {
if (!this.shouldLog(LogLevel.DEBUG)) return;
const timestamp = new Date().toISOString();
const message = label ? `Timestamp '${label}': ${timestamp}` : `Timestamp: ${timestamp}`;
if (typeof console.timeStamp === 'function') {
// Browser environment with timeStamp support
console.timeStamp(label);
console.debug(this.formatMessage(LogLevel.DEBUG, message));
} else {
// Fallback for environments without timeStamp
console.debug(this.formatMessage(LogLevel.DEBUG, message));
}
}
}
if (typeof window !== 'undefined') {
Reflect.set(window, 'Logger', Logger);
}
|