QA Interview Hub · Knowledge base · Quizzes · Українська

Logs and observability › Logs in automation

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.

- name: Collect service logs
  if: ${{ !cancelled() }}
  run: docker compose logs --no-color --timestamps > server.log

- uses: actions/upload-artifact@v7
  if: ${{ !cancelled() }}
  with:
    name: server-logs
    path: server.log
    retention-days: 7

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

1. The test failed in CIthe Playwright report as an artifact2. The report holds the request trace idtestInfo.annotations / attach3. server.log from the same runan artifact with if: !cancelled()4. Search the log by trace idthe first error in the chain
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:

test.afterEach(async ({}, testInfo) => {
  if (testInfo.status !== testInfo.expectedStatus) {
    const log = await fetchServiceLog(testInfo.annotations);
    await testInfo.attach('server-log', {
      body: log,
      contentType: 'text/plain',
    });
  }
});

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 sleep
  await 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.

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.

More articles in this chapter