From b2f69183aa414282cdd233edc1b60a4b7ae42ee6 Mon Sep 17 00:00:00 2001 From: Jack Franklin Date: Mon, 20 Jul 2020 11:05:12 +0100 Subject: [PATCH] fix: configure debug logging in browser (#6210) The Node debug library uses the `DEBUG` environment variable to configure what gets logged. Our browser version just logs everything; this commit changes it to look for `window.__PUPPETEER_DEBUG` and matches the behaviour accordingly: * If the value is not set, nothing is logged. * If the value is set to `*` everything is logged. * If the value is set to a string `foo`, messages with that prefix are logged. * If the value is set to a string ending in `*`, e.g. `foo*`, messages with prefixes that start with `foo` are logged. --- src/common/Debug.ts | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/src/common/Debug.ts b/src/common/Debug.ts index e9a608e3d00eb..8ff124b094b3b 100644 --- a/src/common/Debug.ts +++ b/src/common/Debug.ts @@ -19,6 +19,8 @@ import { isNode } from '../environment.js'; /** * A debug function that can be used in any environment. * + * @remarks + * * If used in Node, it falls back to the * {@link https://www.npmjs.com/package/debug | debug module}. In the browser it * uses `console.log`. @@ -26,6 +28,22 @@ import { isNode } from '../environment.js'; * @param prefix - this will be prefixed to each log. * @returns a function that can be called to log to that debug channel. * + * In Node, use the `DEBUG` environment variable to control logging: + * + * ``` + * DEBUG=* // logs all channels + * DEBUG=foo // logs the `foo` channel + * DEBUG=foo* // logs any channels starting with `foo` + * ``` + * + * In the browser, set `window.__PUPPETEER_DEBUG` to a string: + * + * ``` + * window.__PUPPETEER_DEBUG='*'; // logs all channels + * window.__PUPPETEER_DEBUG='foo'; // logs the `foo` channel + * window.__PUPPETEER_DEBUG='foo*'; // logs any channels starting with `foo` + * ``` + * * @example * ``` * const log = debug('Page'); @@ -40,6 +58,26 @@ export const debug = (prefix: string): ((...args: unknown[]) => void) => { return require('debug')(prefix); } - // eslint-disable-next-line no-console - return (...logArgs: unknown[]): void => console.log(`${prefix}:`, ...logArgs); + return (...logArgs: unknown[]): void => { + const debugLevel = globalThis.__PUPPETEER_DEBUG as string; + if (!debugLevel) return; + + const everythingShouldBeLogged = debugLevel === '*'; + + const prefixMatchesDebugLevel = + everythingShouldBeLogged || + /** + * If the debug level is `foo*`, that means we match any prefix that + * starts with `foo`. If the level is `foo`, we match only the prefix + * `foo`. + */ + (debugLevel.endsWith('*') + ? prefix.startsWith(debugLevel) + : prefix === debugLevel); + + if (!prefixMatchesDebugLevel) return; + + // eslint-disable-next-line no-console + console.log(`${prefix}:`, ...logArgs); + }; };