File
Blob: src/workerd/api/tests/self-logger-test.js
| 1 | // Copyright (c) 2017-2023 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | import * as assert from 'node:assert'; |
| 5 | |
| 6 | // Track if we've received logs in the tail handler |
| 7 | let receivedLogsInTail = false; |
| 8 | |
| 9 | export default { |
| 10 | fetch(request, env) { |
| 11 | // Log some messages that should be captured by the tail handler |
| 12 | console.log('Self-logger test: Message 1'); |
| 13 | console.log('Self-logger test: Message 2'); |
| 14 | console.error(new Error('Self-logger test: Error message')); |
| 15 | |
| 16 | return new Response('Self-logger test completed'); |
| 17 | }, |
| 18 | |
| 19 | // Tail handler in the same worker that generates logs |
| 20 | tail(events) { |
| 21 | console.log(`Self-logger received ${events.length} events`); |
| 22 | |
| 23 | // Check that we have the logs we expect |
| 24 | const logs = []; |
| 25 | for (const event of events) { |
| 26 | if (event.logs) { |
| 27 | for (const log of event.logs) { |
| 28 | logs.push(log.message[0]); |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | // Verify we're seeing the logs from our fetch handler |
| 34 | const foundMessage1 = logs.some((log) => log.includes('Message 1')); |
| 35 | const foundMessage2 = logs.some((log) => log.includes('Message 2')); |
| 36 | const foundError = logs.some((log) => log.includes('Error message')); |
| 37 | |
| 38 | // Assert that we found our logs (this will throw if the test fails) |
| 39 | assert.ok(foundMessage1, 'Should have received "Message 1" in logs'); |
| 40 | assert.ok(foundMessage2, 'Should have received "Message 2" in logs'); |
| 41 | assert.ok(foundError, 'Should have received "Error message" in logs'); |
| 42 | // If we get here, it means the self-logging functionality is working |
| 43 | receivedLogsInTail = true; |
| 44 | }, |
| 45 | }; |
| 46 | |
| 47 | export const test = { |
| 48 | async test(ctrl, env, ctx) { |
| 49 | // This test simply verifies that the self-logger worked |
| 50 | // If the tail handler was called, receivedLogsInTail will be true |
| 51 | const response = await env.SERVICE.fetch('http://example.com/'); |
| 52 | const body = await response.text(); |
| 53 | assert.strictEqual(body, 'Self-logger test completed'); |
| 54 | await scheduler.wait(100); |
| 55 | assert.strictEqual( |
| 56 | receivedLogsInTail, |
| 57 | true, |
| 58 | 'Tail handler should have been called' |
| 59 | ); |
| 60 | }, |
| 61 | }; |