Skip to content

Instantly share code, notes, and snippets.

@32teeth
Created November 1, 2023 16:45
Show Gist options
  • Save 32teeth/e47ac839110c74e27bfe5cd2f909111d to your computer and use it in GitHub Desktop.
Save 32teeth/e47ac839110c74e27bfe5cd2f909111d to your computer and use it in GitHub Desktop.
Puppeteer Logging

Option 1

Wondering if we should enable sloMo

The slowMo option slows down Puppeteer operations by the specified amount of milliseconds. It's another way to help see what's going on.

This

    const config = {
      defaultViewport: {
        height,
        width,
        deviceScaleFactor: 1,
        hasTouch: false,
        isLandscape: true,
        isMobile: false,
      },
      args,
      ...this.props,
    };

To This

    const config = {
      defaultViewport: {
        height,
        width,
        deviceScaleFactor: 1,
        hasTouch: false,
        isLandscape: true,
      },
      args,
      sloMo: 100,  // this line here --> deatails: https://developer.chrome.com/docs/puppeteer/debugging/#slow-it-down
      ...this.props,
    };

Option 2

Wondering if instead of console.log we can somehow implement a save to file this

Option 2.a

This option would require adding this as a file to e2e tst suit

declare global {
  interface Console {
    save(data: any, filename?: string): void;
  }
}

(function (console: Console) {
  console.save = function (data: any, filename?: string): void {
    if (!data) {
      console.error('Console.save: No data');
      return;
    }

    if (!filename) filename = 'console.json';

    if (typeof data === 'object') {
      data = JSON.stringify(data, undefined, 4);
    }

    const blob = new Blob([data], { type: 'text/json' });
    const e = document.createEvent('MouseEvents');
    const a = document.createElement('a');

    a.download = filename;
    a.href = window.URL.createObjectURL(blob);
    a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
  };
})(console);

Usage:

page.on("pageerror", function (err) {
	console.save(`Page error: ${err.toString()}`, 'pageerror.txt');
});

page.on("error", function (err) {
	console.save(`Error: ${err.toString()}`, 'error.txt');
});

Option 2.b

add filestreaming

// In you file add
const fs = require('fs');
const writeStream = fs.createWriteStream('errors.txt');

  page.on('pageerror', function (err) {
    writeStream.write(`Page error: ${err.toString()}\n`);
  });

  page.on('error', function (err) {
    writeStream.write(`Error: ${err.toString()}\n`);
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment