Browser errors in Playwright are caught with page.on events: console, pageerror, requestfailed and response. An event is delivered only to an already subscribed handler, so the subscription is made before the first goto, best as an auto-fixture that checks the error array after the test. The allowlist is kept narrow. For a popup the subscription is made at the context level.
Logs · Test automation
The e2e test is green while the browser console has red exceptions. Does the test not see them?
A checkout test passes every day. Meanwhile the page throws a TypeError in a recommendations widget and a background analytics request returns 500. A user does not notice, and neither does the test: it checks only what it was told to check. A month later the same exception touches the "Pay" button, and it turns out the warning had been visible for a long time. This lesson covers how to make a test see browser errors without making it brittle.
How it works and why. Playwright delivers page events to subscribed handlers. Four matter for diagnostics:
page.on('console', msg => …): console.* calls; msg.type() returns 'error', 'warning', 'log', msg.text() the text, msg.location() the script URL and line.
page.on('pageerror', err => …): unhandled exceptions on the page.
page.on('requestfailed', req => …): network failures (a reset, DNS), but not 4xx/5xx responses.
page.on('response', res => …): all responses; filter on status() >= 500.
The main limitation: an event is delivered only to those already subscribed. Errors that occurred while the page was loading will not be seen by a handler added after page.goto(). Since Playwright 1.56 already received messages can be read back with page.consoleMessages() and page.pageErrors() (up to the last 200), but this is a safety net, not a replacement for subscribing before navigation. So the check is made an auto fixture: it subscribes before the first goto in every test and checks the result at teardown.
When to subscribe
Wrong
After page.goto()
Load-time errors have already passed. The test is green although an exception occurred.
Right
An auto fixture before navigation
The handler is in place before the first request. The rule applies to all tests without duplication.
Figure 1. The order "subscribe, then navigate" decides whether the test sees early errors.
Example: from a hidden exception to a rule in all tests. A test that lets an error through:
The handler is added after goto, so exceptions during loading are lost, and nobody checks the accumulated array. The fix: a fixture with a parameter for allowed exceptions.
After await use(errors) the test has already finished, and the check in the fixture teardown fails it if the array has anything. The allowedErrors option lets you narrow the check for a file or a project:
// known noise of a third-party analytics script: narrow and explained
test.use({ allowedErrors: [/analytics\.example\.com/] });
// a negative scenario: the error is allowed only here
test.describe('payment failure', () => {
test.use({ allowedErrors: [/status of500/] });
test('shows a message', async ({ page }) => {
await page.route('**/api/pay', (r) => r.fulfill({ status: 500 }));
// ...
});
});
Why this way: the allowlist is narrow (a specific domain, not "anything containing error") and explained. Negative scenarios where the error is expected remove noise locally instead of switching the check off everywhere. For known noise from a certain resource (for example a 404 on a favicon) filter by the address from msg.location().url.
Limits and alternatives.page.on listens to one page. For popups and new tabs subscribe at the context level (context.on('console'), context.on('page')) and add handlers to each new page. Errors in an iframe reach the page, while exceptions in workers or extensions may not. The fixture catches only what happened in this run, so it complements functional checks and does not replace them. In Cypress a similar role is played by cy.on('uncaught:exception'), but by default Cypress itself fails a test on an unhandled application exception, whereas Playwright requires a subscription.
Typical mistakes.
Subscribing after goto: early errors vanish.
A broad allowlist "so it does not turn red": the check catches nothing.
Collecting an array and not checking it: errors exist in memory but the test is green.
Switching the fixture off entirely for a negative scenario instead of expecting the error precisely.
Check yourself
The fixture checks errors after await use(errors). Why not inside the test?
Answer
The rule must apply to every test automatically and not depend on whether the test author remembered to call it. The fixture teardown runs after the test body, so everything that happened throughout the test is already collected, and it fails the test if there are errors.
A popup opens in a test and an exception occurs in it. Will the page.on('pageerror') handler of the main page see it?
Answer
No, a popup is a separate page and its events go to its own handlers. Subscribe at the context level through context.on('page') and add handlers to each new page, or listen to context.on('console') for console messages of all pages.
Related lessons: “Server logs in CI, asserting on logs in tests, and logging in the test itself”, “Where to find logs and how to localise a bug with them”, “Secrets and PII in logs, noise and retention”.
In an interview.Junior: I listen to page.on('console') and page.on('pageerror'), collect errors and check there are none. I subscribe before navigating to the page. Middle/Senior: I make it an auto fixture with a narrow allowlist as an option so the rule applies to all tests and does not break on known noise. For popups I subscribe on the context. I know that since Playwright 1.56 early messages can be read back through page.consoleMessages(), but I do not replace subscribing before navigation with it.
Server logs in CI, asserting on logs in tests, and logging in the test itself
A CI runner lives only for the job, so service logs are kept as an artifact and linked to the test through a trace id. The artifact step runs even after tests fail, for example with !cancelled() in GitHub Actions. Logs are asserted in a test only when they are a requirement, by fields and with expect.poll. Test steps are written with test.step.
Logs · Test automation
A test failed in CI and is green locally. The screenshot does not explain why. Where do you look?
In CI the e2e test fails on the "Pay" step with a timeout. The screenshot shows a spinner, the trace shows a hanging request. Why the gateway did not answer is visible only in the application logs for that same minute, but the containers have already been destroyed along with the runner. This lesson covers three things: how to keep server logs from a run, when it makes sense to assert on logs in a test itself, and how to log the test so that the report is useful.
How it works and why. A CI runner exists only for the duration of a job. Everything that remains after it is artifacts. So the logs of the stand’s services must be saved explicitly: either written to a file (docker compose logs) and uploaded as an artifact, or a central store must exist where the run’s logs are found by trace id or time. The second key is the link between the test and the entries: every test request carries its own traceparent or X-Request-Id, and the value is added to the report.
The !cancelled() condition instead of the default is needed so that the step runs after the tests failed (by default the next steps are skipped after a failed one). A cancelled run does not execute the steps, and that is expected. retention-days limits how long the artifact is kept.
From a failure to the root cause
Figure 1. Without step 2 you have to search the server log by time and guesswork.
Example: a server log in the report. So the developer does not download artifacts, an excerpt of the log is attached right to the test report, and only for failed tests:
fetchServiceLog here is your helper: it takes the trace id from the annotations and looks for entries in a store or a file. The advantage: the Playwright report (HTML, trace) becomes the single place of investigation. A caveat: an X-Request-Id header added through extraHTTPHeaders goes to all page requests, including third-party domains, where it can trigger a CORS preflight and break loading. For browser e2e add the header only to your own API requests via page.route.
When to assert on logs in a test. It makes sense when:
a log is part of a requirement (audit of actions, compliance, a security event), not incidental text;
the search is by structured fields and a unique id, not by a message substring;
the wait uses expect.poll or toPass, because logs reach the store with a delay.
test('a payment is written to the audit', async ({ request }) => {
const res = await request.post('/api/orders/8841/pay');
expect(res.ok()).toBeTruthy();
// the event appears with a delay: wait, do not sleepawait expect
.poll(
async () => {
const r = await request.get('/api/audit', { params: { orderId: '8841' } });
return (await r.json()).events.map((e: { type: string }) => e.type);
},
{ timeout: 15_000 },
)
.toContain('order.paid');
});
Here the check goes through an audit API rather than parsing a text file: an event of type order.paid is a contract. If there is no such endpoint, search the log store by fields. It is brittle when a test checks the exact wording of a message, the order of lines or DEBUG logs: any refactoring breaks the test although behaviour has not changed. What matters for the business is better exposed as an event or a metric with a contract.
Logging in the test itself. Steps are made with test.step('…', async () => …): they land in the report and the trace. Diagnostic data (an API response, a log excerpt) is attached with testInfo.attach. console.log all over the code clutters the output, and in parallel workers lines of different tests get mixed, so investigating from it is hard.
Limits and alternatives. CI logs do not replace a central store: that also shows neighbouring services and history. A file collected with docker compose logs sees only the containers of this compose project. If a test run is split across several shards, each job uploads its own artifact with a unique name, otherwise they conflict. Logs may hold secrets, and artifacts are available to everyone who can see the run: see the lesson on PII.
Typical mistakes.
Uploading an artifact without if: !cancelled(): after tests fail the step is skipped, and the logs are missing exactly when they are needed.
Checking message text instead of an event or field: the test breaks on a wording edit.
Sleeping with waitForTimeout before searching the store instead of expect.poll: sometimes slow, sometimes too short.
Not putting the request id into the report: a server log exists but cannot be matched to the test.
Check yourself
Why does the log-collection step in GitHub Actions have an if: !cancelled() condition instead of simply following the tests step?
Answer
By default a step runs only if the previous ones passed. When the tests failed, the logs step would be skipped, yet the logs are needed exactly then. !cancelled() runs the step after a failure but not for a cancelled run.
A test checks that the log has the line "Order 8841 paid". Is this a good logging check?
Answer
No, it is tied to wording and line order and breaks on any edit. Better to search by fields (event type order.paid, orderId) and wait with expect.poll. And if the event matters for the business, expose it as a contract (audit, metric) and check that.
Related lessons: “Browser console and page errors in Playwright”, “Distributed tracing, trace ids and OpenTelemetry”, “Secrets and PII in logs, noise and retention”.
In an interview.Junior: In CI I keep service logs as an artifact and attach them to the report. I make steps in a test with test.step, not console.log. Middle/Senior: I link a test to logs through a trace id in the report, collect artifacts with !cancelled() and unique names for shards. I assert on logs in a test only when it is a requirement (audit), by fields, with expect.poll. I make sure tracing headers go only to our own API and that CI logs have no secrets.
Secrets and PII in logs, noise and retention
Passwords, tokens, full card numbers and personal data must not be written to logs without need, because many people read logs and they are kept long. They are protected by masking at the logger or Collector, an internal id instead of an email and an allowlist of fields. QA checks this with a unique marker, such as a password with a random suffix. Noise hides real errors.
Logs · Security
You see a full card number and a user’s password in the logs. Is that already a leak?
A developer added a "temporary" log of a request body to debug login. A week later fifty people read the logs, they are copied into tickets, they land in a store with long retention and in a third-party analytics service. A password in a log is already out of control. So logs are treated as a separate leak surface, not as safe diagnostics. This lesson covers what must not be logged, how it is protected, how QA checks it, and how not to drown in noise and eternal logs.
How it works and why. Logs are read by many people, kept for long and copied into other systems, so whatever lands there leaks. Do not log passwords, tokens (access, refresh, API keys), full card numbers and CVV, full bodies of authentication requests, or personal data (email, phone, address, a document) unless there is a direct need and a legal basis. For cards, PCI DSS applies: security codes are not stored after authorization, and a number, if needed, is shown masked. A similar list is given by the OWASP Logging Cheat Sheet, and CWE-532 describes the weakness "sensitive information in a log file".
The same log
Wrong
Everything as is
Email, password, a full card with CVV and a token in the clear. Everyone who reads the log sees them.
Right
Masking and an id
An internal id instead of an email, field values replaced, a card with only the last digits.
Figure 1. The purpose of a log: to reconstruct what happened. Secrets are not needed for that.
Example: what is in the log and what should be. A fragment with defects:
INFO login ok user=anna@example.com
INFO POST /auth/login body={"email":"anna@example.com","password":"S3cret!"}
INFO charge card=4111111111111111 cvv=123
DEBUG headers Authorization: Bearer eyJhbGciOi...
The same fragment after the fix:
INFO login ok userId=u_48213
INFO POST /auth/login body={"email":"[redacted]","password":"[redacted]"}
INFO charge card=**** 1111
DEBUG headers Authorization: [redacted]
What is done for this:
Masking: at the logger level or in the OpenTelemetry Collector. Libraries can "redact" fields by path, for example redact in pino:
import pino from'pino';
const logger = pino({
redact: {
// paths to fields that must not reach the log
paths: ['req.headers.authorization', '*.password', '*.cardNumber'],
censor: '[redacted]',
},
});
Log the user’s internal id, not an email or a name.
An allowlist of fields for requests and responses instead of "log everything and cut later": a new field does not get into the log by itself.
DEBUG switched off in production and access control for logs.
The QA role. Check that after login, payment and password reset sensitive values do not appear in logs and error bodies. An automated test does this with a unique marker: a password with a random suffix that must then not be found in the collected server log:
import { execSync } from'node:child_process';
test('a password and a token do not reach the log', async ({ page }) => {
const password = 'S3cret!-' + Date.now();
awaitloginAs(page, 'anna@example.com', password);
// collect this run's log, not the file from the CI stepconst log = execSync('docker compose logs --no-color api').toString();
expect(log).not.toContain(password);
expect(log).not.toMatch(/Bearer\s+[\w-]+\.[\w-]+\.[\w-]+/);
});
The log is collected inside the test, after the action: a file that CI writes after the tests is still missing or stale here. The unique suffix matters: a plain "password" is found in field names and the test would fail falsely. In CI logs GitHub Actions masks the values of registered secrets, but not values derived from them: a base64 version, a substring or a value inside a JSON-structured secret may go unrecognised. So secrets are not printed even "for debugging".
Noise. If there are hundreds of ERRORs every day and nobody looks at them, a real problem will not be noticed. Signs of noise: expected exceptions at ERROR level (for example "user not found" on a wrong login); the same entry thousands of times a second (a retry loop); healthcheck requests per pod. It is fixed with the level, deduplication or a write rate limit, not by switching logging off.
Retention. Logs are kept for a limited time: because of cost and privacy requirements (the storage limitation principle in GDPR: no longer than needed for the purpose). This is automated with index lifecycle policies (in Elasticsearch ILM: hot, warm, cold, frozen, delete). Audit logs may have a longer period. For QA this means that logs and artifacts of a failed run must be read or saved before they vanish, and also that personal data must not stay in logs longer than needed.
Limits and alternatives. Masking by field name does not catch a secret that landed in arbitrary message text ("failed for token abc123"), so it is complemented with secret scanners in CI and regular log checks. Another risk: user input with a line break can forge an entry in a text log (log injection, CWE-117), so control characters are escaped or a structured format is used. Deletion under the right to erasure is hard if PII is spread across logs, and the best protection is not to write it.
Typical mistakes.
A "temporary" request-body log that was forgotten.
A test checks only for the absence of the word "password", not of a specific value.
Copying a log with a token into a public ticket or chat.
Leaving DEBUG on in production "for a couple of days".
Check yourself
A test checks that the server log has no word "password" and fails on every run. What is wrong and how do you check correctly?
Answer
The word "password" occurs in field names and messages ("password reset"), which is not a leak. Check a specific value: enter a unique password with a random suffix and make sure this exact value (and tokens by pattern) is not in the log.
Why is logging an internal id better than a user’s email?
Answer
An id does not reveal a person by itself and still lets you link entries, whereas an email is personal data that then leaks through log copying, requires limited retention and is hard to delete. Only someone with access to the users database can tell who it is.
Related lessons: “What a log entry holds and what the levels mean”, “Server logs in CI, asserting on logs in tests, and logging in the test itself”, “Structured and plain-text logs”.
In an interview.Junior: Passwords, tokens, full cards and personal data must not be written to logs. I check that they are not there after login or payment. Middle/Senior: I ask for masking at the logger or Collector level, an id instead of an email, an allowlist of fields. The automated check goes by a unique marker in the collected log. Separately I look at noise (expected exceptions at ERROR), at retention with lifecycle policies and at log injection.