web/src/utils/logger.ts
57 lines · 2041 bytes
1type Level = 'warn' | 'error';
2
3interface LogEntry {
4 level: Level;
5 source: string;
6 message: string;
7}
8
9// Astro loads the config and the bundled page code as separate instances of
10// this module, so the entries have to live somewhere both of them can see
11const store = globalThis as typeof globalThis & { buildFetchLog?: LogEntry[] };
12const entries = (store.buildFetchLog ??= []);
13
14const MAX_SHOWN_PER_SOURCE = 5;
15
16const plural = (count: number, noun: string) =>
17 `${count} ${noun}${count === 1 ? '' : 's'}`;
18
19export const warn = (source: string, message: string) => {
20 console.warn(`[${source}] ${message}`);
21 entries.push({ level: 'warn', source, message });
22};
23
24export const error = (source: string, message: string) => {
25 console.error(`[${source}] ${message}`);
26 entries.push({ level: 'error', source, message });
27};
28
29export const printSummary = () => {
30 if (!entries.length) return;
31
32 const grouped = new Map<string, LogEntry[]>();
33 for (const entry of entries) {
34 const group = grouped.get(entry.source);
35 if (group) group.push(entry);
36 else grouped.set(entry.source, [entry]);
37 }
38
39 console.log('\n───────────── Build fetch summary ──────────────');
40 for (const [source, group] of grouped) {
41 const errors = group.filter((entry) => entry.level === 'error').length;
42 const warnings = group.length - errors;
43 const tally = [
44 ...(errors ? [plural(errors, 'error')] : []),
45 ...(warnings ? [plural(warnings, 'warning')] : []),
46 ];
47 console.log(`[${source}] ${tally.join(', ')}`);
48 for (const { level, message } of group.slice(0, MAX_SHOWN_PER_SOURCE)) {
49 console.log(` ${level.toUpperCase()}: ${message}`);
50 }
51 const hidden = group.length - MAX_SHOWN_PER_SOURCE;
52 if (hidden > 0) console.log(` ...and ${hidden} more`);
53 }
54 console.log('────────────────────────────────────────────────\n');
55
56 entries.length = 0;
57};