Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: configure debug logging in browser #6210

Merged
merged 1 commit into from Jul 20, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 40 additions & 2 deletions src/common/Debug.ts
Expand Up @@ -19,13 +19,31 @@ 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`.
*
* @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');
Expand All @@ -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);
};
};