Skip to content

Commit

Permalink
feat(logger): introduce context-level logger
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelfeldman committed Apr 21, 2020
1 parent 5d98631 commit 2c468cb
Show file tree
Hide file tree
Showing 24 changed files with 144 additions and 90 deletions.
26 changes: 14 additions & 12 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
- [class: Worker](#class-worker)
- [class: BrowserServer](#class-browserserver)
- [class: BrowserType](#class-browsertype)
- [class: LoggerSink](#class-loggersink)
- [class: Logger](#class-logger)
- [class: ChromiumBrowser](#class-chromiumbrowser)
- [class: ChromiumBrowserContext](#class-chromiumbrowsercontext)
- [class: ChromiumCoverage](#class-chromiumcoverage)
Expand Down Expand Up @@ -218,6 +218,7 @@ Indicates that the browser is connected.
- `username` <[string]>
- `password` <[string]>
- `colorScheme` <"dark"|"light"|"no-preference"> Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See [page.emulateMedia(options)](#pageemulatemediaoptions) for more details. Defaults to '`light`'.
- `logger` <[Logger]> Logger sink for Playwright logging.
- returns: <[Promise]<[BrowserContext]>>

Creates a new browser context. It won't share cookies/cache with other browser contexts.
Expand Down Expand Up @@ -259,6 +260,7 @@ Creates a new browser context. It won't share cookies/cache with other browser c
- `username` <[string]>
- `password` <[string]>
- `colorScheme` <"dark"|"light"|"no-preference"> Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`. See [page.emulateMedia(options)](#pageemulatemediaoptions) for more details. Defaults to '`light`'.
- `logger` <[Logger]> Logger sink for Playwright logging.
- returns: <[Promise]<[Page]>>

Creates a new page in a new browser context. Closing this page will close the context as well.
Expand Down Expand Up @@ -3757,7 +3759,7 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
- `options` <[Object]>
- `wsEndpoint` <[string]> A browser websocket endpoint to connect to. **required**
- `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0.
- `loggerSink` <[LoggerSink]> Sink for log messages.
- `logger` <[Logger]> Logger sink for Playwright logging.
- returns: <[Promise]<[Browser]>>

This methods attaches Playwright to an existing browser instance.
Expand All @@ -3774,7 +3776,7 @@ This methods attaches Playwright to an existing browser instance.
- `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.
- `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.
- `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.
- `loggerSink` <[LoggerSink]> Sink for log messages.
- `logger` <[Logger]> Logger sink for Playwright logging.
- `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- `env` <[Object]> Specify environment variables that will be visible to the browser. Defaults to `process.env`.
- `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`.
Expand Down Expand Up @@ -3807,7 +3809,7 @@ const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
- `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.
- `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.
- `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.
- `loggerSink` <[LoggerSink]> Sink for log messages.
- `logger` <[Logger]> Logger sink for Playwright logging.
- `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- `env` <[Object]> Specify environment variables that will be visible to the browser. Defaults to `process.env`.
- `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`.
Expand All @@ -3826,7 +3828,7 @@ Launches browser instance that uses persistent storage located at `userDataDir`.
- `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.
- `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.
- `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.
- `loggerSink` <[LoggerSink]> Sink for log messages.
- `logger` <[Logger]> Logger sink for Playwright logging.
- `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.
- `env` <[Object]> Specify environment variables that will be visible to the browser. Defaults to `process.env`.
- `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`.
Expand All @@ -3853,7 +3855,7 @@ const { chromium } = require('playwright'); // Or 'webkit' or 'firefox'.

Returns browser name. For example: `'chromium'`, `'webkit'` or `'firefox'`.

### class: LoggerSink
### class: Logger

Playwright generates a lot of logs and they are accessible via the pluggable logger sink.

Expand All @@ -3862,7 +3864,7 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.

(async () => {
const browser = await chromium.launch({
loggerSink: {
logger: {
isEnabled: (name, severity) => name === 'browser',
log: (name, severity, message, args) => console.log(`${name} ${message}`)
}
Expand All @@ -3872,18 +3874,18 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
```

<!-- GEN:toc -->
- [loggerSink.isEnabled(name, severity)](#loggersinkisenabledname-severity)
- [loggerSink.log(name, severity, message, args, hints)](#loggersinklogname-severity-message-args-hints)
- [logger.isEnabled(name, severity)](#loggerisenabledname-severity)
- [logger.log(name, severity, message, args, hints)](#loggerlogname-severity-message-args-hints)
<!-- GEN:stop -->

#### loggerSink.isEnabled(name, severity)
#### logger.isEnabled(name, severity)
- `name` <[string]> logger name
- `severity` <"verbose"|"info"|"warning"|"error">
- returns: <[boolean]>

Determines whether sink is interested in the logger with the given name and severity.

#### loggerSink.log(name, severity, message, args, hints)
#### logger.log(name, severity, message, args, hints)
- `name` <[string]> logger name
- `severity` <"verbose"|"info"|"warning"|"error">
- `message` <[string]|[Error]> log message format
Expand Down Expand Up @@ -4247,7 +4249,7 @@ const { chromium } = require('playwright');
[Frame]: #class-frame "Frame"
[JSHandle]: #class-jshandle "JSHandle"
[Keyboard]: #class-keyboard "Keyboard"
[LoggerSink]: #class-loggersink "LoggerSink"
[Logger]: #class-logger "Logger"
[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"
[Mouse]: #class-mouse "Mouse"
[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"
Expand Down
2 changes: 1 addition & 1 deletion src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export { Dialog } from './dialog';
export { Download } from './download';
export { ElementHandle } from './dom';
export { FileChooser } from './fileChooser';
export { LoggerSink } from './logger';
export { Logger } from './logger';
export { TimeoutError } from './errors';
export { Frame } from './frames';
export { Keyboard, Mouse } from './input';
Expand Down
8 changes: 4 additions & 4 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { EventEmitter } from 'events';
import { Download } from './download';
import type { BrowserServer } from './server/browserServer';
import { Events } from './events';
import { Logger, Log } from './logger';
import { InnerLogger, Log } from './logger';

export interface Browser extends EventEmitter {
newContext(options?: BrowserContextOptions): Promise<BrowserContext>;
Expand All @@ -30,13 +30,13 @@ export interface Browser extends EventEmitter {
close(): Promise<void>;
}

export abstract class BrowserBase extends EventEmitter implements Browser, Logger {
export abstract class BrowserBase extends EventEmitter implements Browser, InnerLogger {
_downloadsPath: string = '';
private _downloads = new Map<string, Download>();
_ownedServer: BrowserServer | null = null;
readonly _logger: Logger;
readonly _logger: InnerLogger;

constructor(logger: Logger) {
constructor(logger: InnerLogger) {
super();
this._logger = logger;
}
Expand Down
13 changes: 8 additions & 5 deletions src/browserContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { Events } from './events';
import { ExtendedEventEmitter } from './extendedEventEmitter';
import { Download } from './download';
import { BrowserBase } from './browser';
import { Log, Logger } from './logger';
import { Log, InnerLogger, Logger, RootLogger } from './logger';

export type BrowserContextOptions = {
viewport?: types.Size | null,
Expand All @@ -43,10 +43,11 @@ export type BrowserContextOptions = {
isMobile?: boolean,
hasTouch?: boolean,
colorScheme?: types.ColorScheme,
acceptDownloads?: boolean
acceptDownloads?: boolean,
logger?: Logger,
};

export interface BrowserContext extends Logger {
export interface BrowserContext extends InnerLogger {
setDefaultNavigationTimeout(timeout: number): void;
setDefaultTimeout(timeout: number): void;
pages(): Page[];
Expand Down Expand Up @@ -79,11 +80,13 @@ export abstract class BrowserContextBase extends ExtendedEventEmitter implements
readonly _permissions = new Map<string, string[]>();
readonly _downloads = new Set<Download>();
readonly _browserBase: BrowserBase;
private _logger: InnerLogger;

constructor(browserBase: BrowserBase, options: BrowserContextOptions) {
super();
this._browserBase = browserBase;
this._options = options;
this._logger = options.logger ? new RootLogger(options.logger) : browserBase;
this._closePromise = new Promise(fulfill => this._closePromiseFulfill = fulfill);
}

Expand Down Expand Up @@ -155,11 +158,11 @@ export abstract class BrowserContextBase extends ExtendedEventEmitter implements
}

_isLogEnabled(log: Log): boolean {
return this._browserBase._isLogEnabled(log);
return this._logger._isLogEnabled(log);
}

_log(log: Log, message: string | Error, ...args: any[]) {
return this._browserBase._log(log, message, ...args);
return this._logger._log(log, message, ...args);
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/chromium/crBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { readProtocolStream } from './crProtocolHelper';
import { Events } from './events';
import { Protocol } from './protocol';
import { CRExecutionContext } from './crExecutionContext';
import { Logger, logError } from '../logger';
import { InnerLogger, logError } from '../logger';

export class CRBrowser extends BrowserBase {
readonly _connection: CRConnection;
Expand All @@ -47,7 +47,7 @@ export class CRBrowser extends BrowserBase {
private _tracingPath: string | null = '';
private _tracingClient: CRSession | undefined;

static async connect(transport: ConnectionTransport, isPersistent: boolean, logger: Logger, slowMo?: number): Promise<CRBrowser> {
static async connect(transport: ConnectionTransport, isPersistent: boolean, logger: InnerLogger, slowMo?: number): Promise<CRBrowser> {
const connection = new CRConnection(SlowMoTransport.wrap(transport, slowMo), logger);
const browser = new CRBrowser(connection, logger, isPersistent);
const session = connection.rootSession;
Expand Down Expand Up @@ -84,7 +84,7 @@ export class CRBrowser extends BrowserBase {
return browser;
}

constructor(connection: CRConnection, logger: Logger, isPersistent: boolean) {
constructor(connection: CRConnection, logger: InnerLogger, isPersistent: boolean) {
super(logger);
this._connection = connection;
this._session = this._connection.rootSession;
Expand Down
6 changes: 3 additions & 3 deletions src/chromium/crConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { assert } from '../helper';
import { ConnectionTransport, ProtocolRequest, ProtocolResponse, protocolLog } from '../transport';
import { Protocol } from './protocol';
import { EventEmitter } from 'events';
import { Logger } from '../logger';
import { InnerLogger } from '../logger';

export const ConnectionEvents = {
Disconnected: Symbol('ConnectionEvents.Disconnected')
Expand All @@ -35,9 +35,9 @@ export class CRConnection extends EventEmitter {
private readonly _sessions = new Map<string, CRSession>();
readonly rootSession: CRSession;
_closed = false;
private _logger: Logger;
private _logger: InnerLogger;

constructor(transport: ConnectionTransport, logger: Logger) {
constructor(transport: ConnectionTransport, logger: InnerLogger) {
super();
this._transport = transport;
this._logger = logger;
Expand Down
12 changes: 6 additions & 6 deletions src/chromium/crCoverage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { Protocol } from './protocol';

import { EVALUATION_SCRIPT_URL } from './crExecutionContext';
import * as types from '../types';
import { logError, Logger } from '../logger';
import { logError, InnerLogger } from '../logger';

type JSRange = {
startOffset: number,
Expand Down Expand Up @@ -51,7 +51,7 @@ export class CRCoverage {
private _jsCoverage: JSCoverage;
private _cssCoverage: CSSCoverage;

constructor(client: CRSession, logger: Logger) {
constructor(client: CRSession, logger: InnerLogger) {
this._jsCoverage = new JSCoverage(client, logger);
this._cssCoverage = new CSSCoverage(client, logger);
}
Expand Down Expand Up @@ -81,9 +81,9 @@ class JSCoverage {
_eventListeners: RegisteredListener[];
_resetOnNavigation: boolean;
_reportAnonymousScripts = false;
private _logger: Logger;
private _logger: InnerLogger;

constructor(client: CRSession, logger: Logger) {
constructor(client: CRSession, logger: InnerLogger) {
this._client = client;
this._logger = logger;
this._enabled = false;
Expand Down Expand Up @@ -175,9 +175,9 @@ class CSSCoverage {
_stylesheetSources: Map<string, string>;
_eventListeners: RegisteredListener[];
_resetOnNavigation: boolean;
private _logger: Logger;
private _logger: InnerLogger;

constructor(client: CRSession, logger: Logger) {
constructor(client: CRSession, logger: InnerLogger) {
this._client = client;
this._logger = logger;
this._enabled = false;
Expand Down
6 changes: 3 additions & 3 deletions src/firefox/ffBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { ConnectionEvents, FFConnection } from './ffConnection';
import { headersArray } from './ffNetworkManager';
import { FFPage } from './ffPage';
import { Protocol } from './protocol';
import { Logger } from '../logger';
import { InnerLogger } from '../logger';

export class FFBrowser extends BrowserBase {
_connection: FFConnection;
Expand All @@ -38,14 +38,14 @@ export class FFBrowser extends BrowserBase {
readonly _firstPagePromise: Promise<void>;
private _firstPageCallback = () => {};

static async connect(transport: ConnectionTransport, logger: Logger, attachToDefaultContext: boolean, slowMo?: number): Promise<FFBrowser> {
static async connect(transport: ConnectionTransport, logger: InnerLogger, attachToDefaultContext: boolean, slowMo?: number): Promise<FFBrowser> {
const connection = new FFConnection(SlowMoTransport.wrap(transport, slowMo), logger);
const browser = new FFBrowser(connection, logger, attachToDefaultContext);
await connection.send('Browser.enable', { attachToDefaultContext });
return browser;
}

constructor(connection: FFConnection, logger: Logger, isPersistent: boolean) {
constructor(connection: FFConnection, logger: InnerLogger, isPersistent: boolean) {
super(logger);
this._connection = connection;
this._ffPages = new Map();
Expand Down
6 changes: 3 additions & 3 deletions src/firefox/ffConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { EventEmitter } from 'events';
import { assert } from '../helper';
import { ConnectionTransport, ProtocolRequest, ProtocolResponse, protocolLog } from '../transport';
import { Protocol } from './protocol';
import { Logger } from '../logger';
import { InnerLogger } from '../logger';

export const ConnectionEvents = {
Disconnected: Symbol('Disconnected'),
Expand All @@ -33,7 +33,7 @@ export class FFConnection extends EventEmitter {
private _lastId: number;
private _callbacks: Map<number, {resolve: Function, reject: Function, error: Error, method: string}>;
private _transport: ConnectionTransport;
private _logger: Logger;
private _logger: InnerLogger;
readonly _sessions: Map<string, FFSession>;
_closed: boolean;

Expand All @@ -43,7 +43,7 @@ export class FFConnection extends EventEmitter {
removeListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;
once: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;

constructor(transport: ConnectionTransport, logger: Logger) {
constructor(transport: ConnectionTransport, logger: InnerLogger) {
super();
this._transport = transport;
this._logger = logger;
Expand Down
6 changes: 3 additions & 3 deletions src/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import * as types from './types';
import * as dom from './dom';
import { helper } from './helper';
import { Logger } from './logger';
import { InnerLogger } from './logger';

export interface ExecutionContextDelegate {
evaluate(context: ExecutionContext, returnByValue: boolean, pageFunction: string | Function, ...args: any[]): Promise<any>;
Expand All @@ -29,9 +29,9 @@ export interface ExecutionContextDelegate {

export class ExecutionContext {
readonly _delegate: ExecutionContextDelegate;
readonly _logger: Logger;
readonly _logger: InnerLogger;

constructor(delegate: ExecutionContextDelegate, logger: Logger) {
constructor(delegate: ExecutionContextDelegate, logger: InnerLogger) {
this._delegate = delegate;
this._logger = logger;
}
Expand Down
Loading

0 comments on commit 2c468cb

Please sign in to comment.