Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 5 additions & 23 deletions bin/lib/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,6 @@ class Logger {
this.levels = { error: 0, warn: 1, info: 2, debug: 3 };
this.currentLevelPriority = this.levels[this.level] ?? this.levels.info;
this.logStream = null;
this.initConsoleLogging();
}

initConsoleLogging() {
if (DEBUG) {
this.logStream = fs.createWriteStream('playwright-server.log', { flags: 'a' });
const originalConsoleLog = console.log;
console.log = (d) => {
this.logStream.write(new Date().toISOString() + ' - ' + d + '\n');
originalConsoleLog(d);
};
}
}

shouldLog(level) {
Expand All @@ -39,16 +27,10 @@ class Logger {
if (!this.shouldLog(level)) return;
const timestamp = new Date().toISOString();
let logMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
if (data) {
if (typeof data === 'object') {
try {
logMessage += `\n${JSON.stringify(data, null, 2)}`;
} catch (e) {
logMessage += ` [Object: ${String(data)}]`;
}
} else {
logMessage += ` ${data}`;
}
if (data && typeof data === 'object') {
const fields = ['action', 'method', 'requestId', 'pageId', 'contextId', 'browserId', 'serverId', 'routeId', 'ownerId', 'pid', 'type', 'reason'];
data = Object.fromEntries(Object.entries(data).filter(([key]) => fields.includes(key)));
logMessage += `\n${JSON.stringify(data, null, 2)}`;
}
logMessage += '\n';
try {
Expand Down Expand Up @@ -378,6 +360,6 @@ class RouteUtils {
const logger = new Logger();

module.exports = {
logger, ErrorHandler, LspFraming, sendFramedResponse,
Logger, logger, ErrorHandler, LspFraming, sendFramedResponse,
CommandRegistry, NavigationRedirects, BaseHandler, PromiseUtils, FrameUtils, RouteUtils,
};
7 changes: 0 additions & 7 deletions src/Browser/BrowserBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
use Playwright\Configuration\PlaywrightConfig;
use Playwright\Exception\MissingDependencyException;
use Playwright\Exception\PlaywrightException;
use Playwright\Transport\Sanitizer;
use Playwright\Transport\TransportInterface;
use Psr\Log\LoggerInterface;

Expand Down Expand Up @@ -116,10 +115,8 @@ public function launch(): BrowserInterface
], $this->config->toContextOptions());
}

// Launch options can carry proxy credentials, so never log them raw.
$this->logger->info('Launching browser', [
'browser' => $this->browserType,
'options' => Sanitizer::sanitizeParams($this->launchOptions),
]);

$response = $this->transport->send([
Expand Down Expand Up @@ -177,8 +174,6 @@ private function connectToBrowserServer(string $wsEndpoint, array $options, arra
{
$this->logger->info('Connecting to browser server', [
'browser' => $this->browserType,
'wsEndpoint' => Sanitizer::sanitizeUrl($wsEndpoint),
'options' => Sanitizer::sanitizeParams($options),
]);

$payload = [
Expand Down Expand Up @@ -230,8 +225,6 @@ public function connectOverCDP(string $endpointURL, array $options = []): Browse
{
$this->logger->info('Connecting over CDP', [
'browser' => $this->browserType,
'endpointURL' => Sanitizer::sanitizeUrl($endpointURL),
'options' => Sanitizer::sanitizeParams($options),
]);

$response = $this->transport->send([
Expand Down
3 changes: 2 additions & 1 deletion src/Frame/Frame.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
use Playwright\Page\Options\WaitForNavigationOptions;
use Playwright\Page\Options\WaitForUrlOptions;
use Playwright\Page\PageInterface;
use Playwright\Transport\MetadataLogger;
use Playwright\Transport\TransportInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
Expand All @@ -48,7 +49,7 @@ public function __construct(
?LoggerInterface $logger = null,
private readonly ?PageInterface $page = null,
) {
$this->logger = $logger ?? new NullLogger();
$this->logger = MetadataLogger::wrap($logger ?? new NullLogger());
}

public function __toString(): string
Expand Down
3 changes: 2 additions & 1 deletion src/Frame/FrameLocator.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Playwright\Locator\LocatorInterface;
use Playwright\Locator\RoleSelectorBuilder;
use Playwright\Page\PageInterface;
use Playwright\Transport\MetadataLogger;
use Playwright\Transport\TransportInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
Expand All @@ -33,7 +34,7 @@ public function __construct(
?LoggerInterface $logger = null,
private readonly ?PageInterface $page = null,
) {
$this->logger = $logger ?? new NullLogger();
$this->logger = MetadataLogger::wrap($logger ?? new NullLogger());
}

public function locator(string $selector): LocatorInterface
Expand Down
6 changes: 2 additions & 4 deletions src/Locator/Locator.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
use Playwright\Locator\Options\WaitForOptions;
use Playwright\Page\PageInterface;
use Playwright\Screenshot\ScreenshotComparison;
use Playwright\Transport\Sanitizer;
use Playwright\Transport\MetadataLogger;
use Playwright\Transport\TransportInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
Expand Down Expand Up @@ -81,7 +81,7 @@ public function __construct(
array $options = [],
private readonly ?PageInterface $page = null,
) {
$this->logger = $logger ?? new NullLogger();
$this->logger = MetadataLogger::wrap($logger ?? new NullLogger());
$this->options = $options;
if ($selector instanceof SelectorChain) {
$this->selectorChain = $selector;
Expand Down Expand Up @@ -515,7 +515,6 @@ public function setInputFiles(string|array $files, array|SetInputFilesOptions $o
$this->logger->error('Failed to set input files on locator', [
'selector' => (string) $this->selectorChain,
'files' => $fileArray,
'error' => Sanitizer::sanitizeParams($e->getMessage()),
'exceptionType' => $e::class,
]);
throw $e;
Expand Down Expand Up @@ -819,7 +818,6 @@ private function sendCommand(string $action, array $params = []): array
$errorMessage = is_string($error) ? $error : 'Unknown locator error';
$this->logger->error('Locator command failed', [
'action' => $action,
'error' => Sanitizer::sanitizeParams($errorMessage),
]);

throw new PlaywrightException($errorMessage);
Expand Down
11 changes: 4 additions & 7 deletions src/Page/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
use Playwright\Screencast\ScreencastInterface;
use Playwright\Screenshot\ScreenshotComparison;
use Playwright\Screenshot\ScreenshotHelper;
use Playwright\Transport\MetadataLogger;
use Playwright\Transport\Sanitizer;
use Playwright\Transport\TransportInterface;
use Playwright\Video\Video;
Expand Down Expand Up @@ -131,7 +132,7 @@ public function __construct(
private readonly PlaywrightConfig $config,
?LoggerInterface $logger = null,
) {
$this->logger = $logger ?? $config->logger ?? new NullLogger();
$this->logger = MetadataLogger::wrap($logger ?? $config->logger ?? new NullLogger());

$this->keyboard = new Keyboard($this->transport, $this->pageId);
$this->mouse = new Mouse($this->transport, $this->pageId);
Expand Down Expand Up @@ -382,7 +383,6 @@ public function goto(string $url, array|GotoOptions $options = []): ?ResponseInt
} catch (\Throwable $e) {
$this->logger->error('Failed to navigate to URL', [
'url' => $logUrl,
'error' => Sanitizer::sanitizeParams($e->getMessage()),
'exceptionType' => $e::class,
]);
throw $e;
Expand Down Expand Up @@ -421,7 +421,6 @@ public function screenshot(?string $path = null, array|ScreenshotOptions $option
} catch (\Throwable $e) {
$this->logger->error('Failed to take screenshot', [
'path' => $finalPath,
'error' => Sanitizer::sanitizeParams($e->getMessage()),
'exceptionType' => $e::class,
]);
throw $e;
Expand Down Expand Up @@ -505,7 +504,6 @@ public function pdf(?string $path = null, array|PdfOptions $options = []): strin
} catch (\Throwable $e) {
$this->logger->error('Failed to generate PDF', [
'path' => $finalPath,
'error' => Sanitizer::sanitizeParams($e->getMessage()),
'exceptionType' => $e::class,
]);

Expand Down Expand Up @@ -852,7 +850,7 @@ private function sendCommand(string $action, array $params = []): array
$error = $response['error'];
if (!is_array($error)) {
$message = is_string($error) ? $error : 'Unknown error';
$this->logger->error('Playwright server error (non-structured)', ['error' => Sanitizer::sanitizeParams($error)]);
$this->logger->error('Playwright server error (non-structured)', ['pageId' => $this->pageId]);
if (str_contains($message, 'Timeout')) {
throw new TimeoutException($message);
}
Expand All @@ -867,7 +865,7 @@ private function sendCommand(string $action, array $params = []): array
$message = 'Unknown error';
}

$this->logger->error('Playwright server error', ['error' => Sanitizer::sanitizeParams($error)]);
$this->logger->error('Playwright server error', ['pageId' => $this->pageId]);

if (str_contains($message, 'Target page, context or browser has been closed')) {
throw new PlaywrightException('Browser context has been closed');
Expand Down Expand Up @@ -1430,7 +1428,6 @@ public function setInputFiles(string $selector, array $files, array|SetInputFile
$this->logger->error('Failed to set input files', [
'selector' => $selector,
'files' => $files,
'error' => Sanitizer::sanitizeParams($e->getMessage()),
'exceptionType' => $e::class,
]);
throw $e;
Expand Down
2 changes: 1 addition & 1 deletion src/PlaywrightClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public function webkit(): BrowserBuilder
public function launchServer(string $browser, array $options = []): BrowserServerInterface
{
$this->connect();
$this->logger->debug('Launching browser server', ['browser' => $browser, 'options' => $options]);
$this->logger->debug('Launching browser server', ['browser' => $browser]);

$response = $this->transport->send([
'action' => 'launchServer',
Expand Down
4 changes: 2 additions & 2 deletions src/Transport/JsonRpc/JsonRpcTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ public function send(array $message): array
return $this->client->sendRaw($message, $timeoutMs);
} catch (\Throwable $e) {
$this->logger->error('JSON-RPC send failed', [
'error' => $e->getMessage(),
'exceptionType' => $e::class,
'action' => $message['action'] ?? 'unknown',
]);
throw $e;
Expand Down Expand Up @@ -339,7 +339,7 @@ public function sendAsync(array $message): void
$this->sendAsyncMessage($message);
} catch (\Throwable $e) {
$this->logger->warning('JSON-RPC sendAsync failed', [
'error' => $e->getMessage(),
'exceptionType' => $e::class,
'method' => $message['action'] ?? 'unknown',
]);
}
Expand Down
8 changes: 4 additions & 4 deletions src/Transport/JsonRpc/ProcessJsonRpcClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ protected function sendAndReceive(array $request, ?float $deadline): array
$framedMessage = LspFraming::encode($json);

$this->logger->debug('Sending JSON-RPC request to process', [
'json' => $json,
'action' => $request['action'] ?? $request['method'] ?? null,
'requestId' => $requestId,
'pid' => $this->process->getPid(),
]);

Expand Down Expand Up @@ -140,7 +141,7 @@ private function readProcessOutput(): void
$stderr = $this->process->getIncrementalErrorOutput();
$this->process->clearErrorOutput();
if ('' !== $stderr) {
$this->logger->warning('Process stderr', ['stderr' => Sanitizer::sanitizeString($stderr)]);
$this->logger->warning('Process stderr', ['bytes' => strlen($stderr)]);
}

$this->processAndDispatchMessages();
Expand Down Expand Up @@ -172,7 +173,7 @@ private function dispatchMessage(string $messageContent): void

return;
}
$this->logger->warning('Received non-array JSON from process', ['message' => $messageContent]);
$this->logger->warning('Received non-array JSON from process');

return;
}
Expand Down Expand Up @@ -228,7 +229,6 @@ private function dispatchMessage(string $messageContent): void
return;
}
$this->logger->warning('Failed to parse JSON from process', [
'message' => $messageContent,
'error' => $e->getMessage(),
]);
}
Expand Down
43 changes: 43 additions & 0 deletions src/Transport/MetadataLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

/*
* This file is part of the community-maintained Playwright PHP project.
* It is not affiliated with or endorsed by Microsoft.
*
* (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Playwright\Transport;

use Psr\Log\AbstractLogger;
use Psr\Log\LoggerInterface;

/** @internal */
final class MetadataLogger extends AbstractLogger
{
private const FIELDS = ['action', 'pageId', 'contextId', 'requestId', 'browser', 'method', 'exceptionType', 'fileCount', 'pid', 'index'];

public function __construct(private readonly LoggerInterface $logger)
{
}

public static function wrap(LoggerInterface $logger): LoggerInterface
{
if ($logger instanceof self) {
return $logger;
}

return new self($logger);
}

/** @param array<string, mixed> $context */
public function log($level, string|\Stringable $message, array $context = []): void
{
$this->logger->log($level, $message, array_intersect_key($context, array_flip(self::FIELDS)));
}
}
32 changes: 32 additions & 0 deletions tests/Integration/Bridge/DiagnosticsBridgeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

/*
* This file is part of the community-maintained Playwright PHP project.
* It is not affiliated with or endorsed by Microsoft.
*
* (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Playwright\Tests\Integration\Bridge;

use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Process;

#[CoversNothing]
final class DiagnosticsBridgeTest extends TestCase
{
public function testBridgeBoundariesAndResourceLifetimes(): void
{
$process = new Process(['node', '--test', __DIR__.'/diagnostics.test.cjs']);
$process->setTimeout(30);
$process->run();

$this->assertSame(0, $process->getExitCode(), $process->getOutput().$process->getErrorOutput());
}
}
26 changes: 26 additions & 0 deletions tests/Integration/Bridge/diagnostics.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { mkdtempSync, readFileSync, rmSync } = require('node:fs');
const { tmpdir } = require('node:os');
const path = require('node:path');
const { Logger } = require('../../../bin/lib/core');

test('diagnostics keep command metadata and omit arbitrary payloads', () => {
const directory = mkdtempSync(path.join(tmpdir(), 'playwright-log-'));
try {
const logger = new Logger();
logger.enabled = true;
logger.logPath = path.join(directory, 'dispatch.log');
logger.info('Dispatching command', {
action: 'locator.fill', requestId: 1, value: 'fill-secret',
error: 'Call log: Authorization: header-secret',
url: 'https://user:password@example.test?token=url-secret',
callbackResult: { cookies: [{ name: 'session', value: 'cookie-secret' }] },
});
const log = readFileSync(logger.logPath, 'utf8');
assert.match(log, /locator.fill/);
for (const secret of ['fill-secret', 'header-secret', 'url-secret', 'cookie-secret', 'password']) assert.equal(log.includes(secret), false);
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
2 changes: 1 addition & 1 deletion tests/Integration/Browser/BrowserBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ public function itDoesNotLogTheProxyPassword(): void
$logger->expects($this->once())
->method('info')
->with('Launching browser', $this->callback(static function (array $context): bool {
return '[REDACTED]' === $context['options']['proxy']['password'];
return ['browser' => 'chromium'] === $context;
}));

$transport = $this->createMock(TransportInterface::class);
Expand Down
Loading
Loading