How to Capture Browser Logs with Playwright
In this article
Capturing browser logs—including console messages, exceptions, HTTP requests, and network failures—enables precise debugging of web applications during automated testing with Playwright. By collecting these logs, you can detect JavaScript errors, monitor API calls, and identify failed resources that might otherwise go unnoticed. This guide walks through setting up Playwright to capture and inspect all relevant browser-level output programmatically, ensuring comprehensive visibility into your application’s runtime behavior.
What You'll Need
- Node.js installed (v14 or higher recommended)
- Playwright library installed via
npm install @playwright/testornpm install playwright - A working Playwright script (e.g., launching a browser and navigating to a page)
- Basic understanding of JavaScript or TypeScript
- A test or production web page that generates console output or network activity
Step-by-Step
- Launch browser with logging enabled: Start by launching a browser context with the
ignoreHTTPSErrorsoption if testing on HTTPS sites with self-signed certificates, and ensure you capture events via listeners. Usebrowser.newContext()to set up proper event handling. - Enable console message capture: Subscribe to the
consoleevent on the page. Usepage.on('console', message => { ... })to intercept all console logs (log, info, warn, error). Store messages in an array for later inspection. - Capture JavaScript exceptions: Attach a listener to the
pageerrorevent, which fires when uncaught exceptions occur in the page’s JavaScript. Usepage.on('pageerror', exception => { ... })and push the error details (message, stack trace) into a structured log array. - Monitor network requests and failures: Listen to
request,response, andrequestfailedevents. Usepage.on('request', req => { ... })to log all outgoing requests,page.on('response', res => { ... })for successful responses, andpage.on('requestfailed', req => { ... })to catch failed network calls (e.g., 404, 500, timeouts). - Log request details: For each network event, extract key data such as URL, method, status code, headers, and failure text. For failed requests, use
req.failure().errorTextto get the reason (e.g., 'net::ERR_CONNECTION_REFUSED'). - Preserve logs across page navigations: If your test involves multiple page loads, declare your log arrays and event listeners outside navigation steps or re-attach them after
page.goto(). Alternatively, use the browser context level to catch events across multiple pages. - Print or export logs after test execution: After closing the page or context, output collected logs to the console, a file, or a reporting tool. Use
console.log(JSON.stringify(logs, null, 2))for structured debugging. - Use Playwright Test for structured reporting: If using
@playwright/test, leveragetest.info().attach()to save logs as artifacts. This integrates logs directly into test reports and enables easier post-run analysis. - Filter logs for relevance: In production scripts, avoid logging every request. Instead, filter by URL patterns (e.g., only log API endpoints) or error levels (e.g., ignore info, capture only warnings and errors).
- Verify log capture with a test page: Create or navigate to a test page that intentionally throws a console error, makes a failed XHR request, and logs messages. Confirm your script captures all three types of output correctly.
Common Mistakes
- Forgetting to attach event listeners before navigation—logs emitted before the listener is set are missed.
- Not capturing both
consoleandpageerror—uncaught exceptions won't appear in console logs. - Assuming
requestfailedincludes status codes—it doesn’t; only successful responses have status codes. Usereq.failure()to get network-level errors. - Overloading logs by capturing every request without filtering, making it hard to find relevant issues.
- Using
page.on()inside asynchronous callbacks without proper scoping, leading to missed events.
Tips
- Use structured logging: store logs as objects with timestamps, types, and metadata for easier analysis.
- Group logs by test or page session using unique IDs to correlate events across runs.
- Combine console and network logs to trace errors back to specific API calls or scripts.
- Set a maximum log size to prevent memory issues during long-running tests.
- Use Playwright’s built-in debug tools like
playwright show-traceto visualize captured logs alongside test steps.
Troubleshooting
If logs are not captured, first verify that event listeners are attached before any page activity. Delayed attachment is the most common cause. Use console.log inside each listener to confirm they are firing. If pageerror events are missing, ensure the error is uncaught—wrapped exceptions won’t trigger it. For missing network failures, confirm the request actually fails (some timeouts may succeed eventually). If using Playwright Test, check that testInfo is used correctly to preserve logs across fixtures. In headless mode, some browser behaviors differ—run in headed mode (headless: false) temporarily to verify expected network behavior. If logs appear truncated, increase Node.js memory limits or write logs to disk incrementally.
Frequently Asked Questions
Does Playwright capture console logs from iframes?
Yes, Playwright captures console logs from all frames within a page, including iframes, as long as the listener is attached to the main page object.
Can I capture logs from before the page loads?
No. You must attach the console and pageerror listeners before navigation. Any logs emitted during initial load will be missed if the listener is added after page.goto().
How do I capture HTTP headers in failed requests?
You cannot retrieve response headers from failed requests because no response was received. However, you can log request headers using request.headers() before the request is sent.
Is it possible to capture browser console logs in CI/CD pipelines?
Yes. Playwright runs headlessly in CI environments and captures logs the same way. Use test.info().attach() in Playwright Test to save logs as artifacts for later inspection.
Why are some console messages not appearing in my logs?
This usually happens if the listener is attached too late. Ensure page.on('console') is set immediately after creating the page instance, before any navigation or interaction.
Can I filter logs by severity level (e.g., only errors)?
Yes. Check the message.type() in the console event (e.g., 'error', 'warning') and only process or store messages matching your desired level.