-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathconsoleFormatter.ts
More file actions
63 lines (53 loc) · 1.45 KB
/
consoleFormatter.ts
File metadata and controls
63 lines (53 loc) · 1.45 KB
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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type {ConsoleMessage, JSHandle} from 'puppeteer-core';
const logLevels: Record<string, string> = {
log: 'Log',
info: 'Info',
warning: 'Warning',
error: 'Error',
exception: 'Exception',
assert: 'Assert',
};
export async function formatConsoleEvent(
event: ConsoleMessage | Error,
): Promise<string> {
// Check if the event object has the .type() method, which is unique to ConsoleMessage
if ('type' in event) {
return await formatConsoleMessage(event);
}
return `Error: ${event.message}`;
}
async function formatConsoleMessage(msg: ConsoleMessage): Promise<string> {
const logLevel = logLevels[msg.type()];
const text = msg.text();
const args = msg.args();
const formattedArgs = await formatArgs(args, text);
return `${logLevel}> ${text} ${formattedArgs}`.trim();
}
// Only includes the first arg and indicates that there are more args
async function formatArgs(
args: readonly JSHandle[],
messageText: string,
): Promise<string> {
if (args.length === 0) {
return '';
}
let formattedArgs = '';
const firstArg = await args[0].jsonValue().catch(() => {
// Ignore errors
});
if (firstArg !== messageText) {
formattedArgs +=
typeof firstArg === 'object'
? JSON.stringify(firstArg)
: String(firstArg);
}
if (args.length > 1) {
return `${formattedArgs} ...`;
}
return formattedArgs;
}