綜合監控的範例

本文說明可用的範本和程式碼範例,協助您建立綜合監控作業。您可以在 Google Cloud/synthetics-sdk-nodjs GitHub 存放區中找到範例函式。

如果您撰寫測試時並未依賴範本,請確保測試通過,除非擲回 Error。建議您使用 Assert 程式庫,確保發生失敗時,系統會將失敗歸因於正確的程式碼行。

一般範本

一般範本已設定為收集外送 HTTP 要求的追蹤和記錄資料。這項解決方案採用 OpenTelemetry auto-instrumentation-node 模組和 winston 記錄器。由於這項功能依賴開放原始碼產品,追蹤記錄和記錄檔資料的結構可能會有所變更。因此,收集到的追蹤記錄和記錄資料應僅用於偵錯。

您可以自行實作方法,收集傳出 HTTP 要求的追蹤和記錄資料。如需自訂做法的範例,請參閱 SyntheticAutoInstrumentation 類別。

一般 Node.js 範例

generic-synthetic-nodejs 範例說明如何查詢網址。這個範例與 Google Cloud 控制台顯示的預設函式相同。如要查看完整範例,請按一下「更多」圖示 ,然後選取「在 GitHub 上查看」

const { instantiateAutoInstrumentation, runSyntheticHandler } = require('@google-cloud/synthetics-sdk-api');
// Run instantiateAutoInstrumentation before any other code runs, to get automatic logs and traces
instantiateAutoInstrumentation();
const functions = require('@google-cloud/functions-framework');
const axios = require('axios');
const assert = require('node:assert');

functions.http('SyntheticFunction', runSyntheticHandler(async ({logger, executionId}) => {
  /*
   * This function executes the synthetic code for testing purposes.
   * If the code runs without errors, the synthetic test is considered successful.
   * If an error is thrown during execution, the synthetic test is considered failed.
   */
  logger.info('Making an http request using synthetics, with execution id: ' + executionId);
  const url = 'https://www.google.com/'; // URL to send the request to
  return await assert.doesNotReject(axios.get(url));
}));

TypeScript 範例

generic-synthetic-typescript 範例說明如何查詢網址。如要查看完整範例,請按一下「更多」圖示 ,然後選取「在 GitHub 上查看」

import {runSyntheticHandler, instantiateAutoInstrumentation} from '@google-cloud/synthetics-sdk-api'
// Run instantiateAutoInstrumentation before any other code runs, to get automatic logs and traces
instantiateAutoInstrumentation();
import * as ff from '@google-cloud/functions-framework';
import axios from 'axios';
import assert from 'node:assert';
import {Logger} from 'winston';

ff.http('SyntheticFunction', runSyntheticHandler(async ({logger, executionId}: {logger: Logger, executionId: string|undefined}) => {
  /*
   * This function executes the synthetic code for testing purposes.
   * If the code runs without errors, the synthetic test is considered successful.
   * If an error is thrown during execution, the synthetic test is considered failed.
   */
  logger.info('Making an http request using synthetics, with execution id: ' + executionId);
  const url = 'https://www.google.com/'; // URL to send the request to
  return await assert.doesNotReject(axios.get(url));
}));

Puppeteer 範本

如果您使用 Puppeteer,建議從 generic-puppeteer-nodejs 範例開始。

必須設定 Puppeteer

如要使用 Puppeteer,請務必完成下列步驟:

  1. 在 Cloud Run 函式的來源目錄中加入 .puppeteerrc.cjs

    const { join } = require('path');
    
    /**
     * @type {import("puppeteer").Configuration}
     */
    module.exports = {
      cacheDirectory: join(__dirname, '.cache', 'puppeteer'),
    };
  2. 將下列指令碼新增至 Cloud Run 函式的 package.json 檔案:

    "scripts": {
         "gcp-build": "node node_modules/puppeteer/install.mjs"
    },
    

Puppeteer 範例

generic-puppeteer-nodejs 範例說明如何搭配 Cloud Run 函式使用 Puppeteer。如要查看完整範例,請按一下「更多」圖示 ,然後選取「在 GitHub 上查看」

const { instantiateAutoInstrumentation, runSyntheticHandler } = require('@google-cloud/synthetics-sdk-api');
// Run instantiateAutoInstrumentation before any other code runs, to get automatic logs and traces
instantiateAutoInstrumentation();
const functions = require('@google-cloud/functions-framework');
const axios = require('axios');
const assert = require('node:assert');
const puppeteer = require('puppeteer');


functions.http('CustomPuppeteerSynthetic', runSyntheticHandler(async ({logger, executionId}) => {
 /*
  * This function executes the synthetic code for testing purposes.
  * If the code runs without errors, the synthetic test is considered successful.
  * If an error is thrown during execution, the synthetic test is considered failed.
  */

 // Launch a headless Chrome browser and open a new page
 const browser = await puppeteer.launch({ headless: 'new', timeout: 0});
 const page = await browser.newPage();

 // Navigate to the target URL
 const result = await page.goto('https://www.example.com', {waitUntil: 'load'});

 // Confirm successful navigation
 await assert.equal(result.status(), 200);

 // Print the page title to the console
 const title = await page.title();
 logger.info(`My Page title: ${title} ` + executionId);

 // Close the browser
 await browser.close();
}));

Selenium WebDriver 範本

如果您使用 Selenium WebDriver,建議從 generic-selenium-nodejs 範例開始。GitHub 上的範例包含 index.jspackage.json 檔案。

如要查看完整範例,請按一下「更多」圖示 ,然後選取「在 GitHub 上查看」

const {
  instantiateAutoInstrumentation,
  runSyntheticHandler,
} = require('@google-cloud/synthetics-sdk-api');
// Run instantiateAutoInstrumentation before any other code runs, to get automatic logs and traces
instantiateAutoInstrumentation();
const functions = require('@google-cloud/functions-framework');
const assert = require('node:assert');

const { Builder, Browser, By } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

/*
 * This function executes the synthetic code for testing purposes.
 * If the code runs without errors, the synthetic test is considered successful.
 * If an error is thrown during execution, the synthetic test is considered failed.
 */
functions.http(
  'CustomSeleniumSynthetic',
  runSyntheticHandler(async ({ logger, executionId }) => {
    /*
     * Construct chrome options
     * Note: `setChromeBinaryPath` must be set to '/srv/bin/chromium' when running in
     *   GCF (but will need to be changed if running on local machine).
     */
    const options = new chrome.Options();
    options.setChromeBinaryPath('/srv/bin/chromium');
    options.addArguments('--headless', '--disable-gpu', '--no-sandbox');

    // Launch headless chrome webdriver with options
    const driver = await new Builder()
      .forBrowser(Browser.CHROME)
      .setChromeOptions(options)
      .build();

    // Navigate to the target URL
    await driver.get('https://example.com');

    // Retrieve title and `a` tag of page
    const title = await driver.getTitle();
    const aTag = await driver.findElement(By.css('a')).getText();

    // assert title is as expected and print to console
    await assert.equal(title, 'Example Domain');
    logger.info(`My URL title is: ${title} ` + executionId);

    await driver.quit();
  })
);

Mocha 範本

如果您編寫的測試依賴 Mocha 範本,請考慮發生失敗時,是否應繼續或停止執行一系列測試。如要在失敗後停止測試序列,您必須設定 bail 旗標。

如需端對端範例,包括部署 API、API 端點的範例 Mocha 測試套件,以及如何設定合成監控,請參閱「Google Cloud 合成監控教學課程」網誌。

mocha-url-ok 範例說明 Cloud Run 函式如何叫用 Mocha 測試套件,並提供範例測試套件。如要查看完整範例,請按一下「更多」圖示 ,然後選取「在 GitHub 上查看」


const functions = require('@google-cloud/functions-framework');
const GcmSynthetics = require('@google-cloud/synthetics-sdk-mocha');

/*
 * This is the server template that is required to run a synthetic monitor in
 * Google Cloud Functions.
 */

functions.http('SyntheticMochaSuite', GcmSynthetics.runMochaHandler({
  spec: `${__dirname}/mocha_tests.spec.js`
}));

/*
 * This is the file may be interacted with to author mocha tests. To interact
 * with other GCP products or services, users should add dependencies to the
 * package.json file, and require those dependencies here A few examples:
 *  - @google-cloud/secret-manager:
 *        https://www.npmjs.com/package/@google-cloud/secret-manager
 *  - @google-cloud/spanner: https://www.npmjs.com/package/@google-cloud/spanner
 *  - Supertest: https://www.npmjs.com/package/supertest
 */

const {expect} = require('chai');
const fetch = require('node-fetch');

it('pings my website', async () => {
  const url = 'https://google.com/'; // URL to send the request to
  const externalRes = await fetch(url);
  expect(externalRes.ok).to.be.true;
});

broken-links-ok 範例說明如何設定失效連結檢查工具。在這個範本中,您只需要指定 options 物件的值。這個物件會指定要測試的 URI,以及測試的參數。

如果您使用 Puppeteer,請務必完成「必要 Puppeteer 設定」步驟。

如要查看完整範例,請按一下「更多」圖示 ,然後選取「在 GitHub 上查看」


const functions = require('@google-cloud/functions-framework');
const GcmSynthetics = require('@google-cloud/synthetics-sdk-broken-links');

const options = {
  origin_uri: "https://example.com",
  // link_limit: 10,
  // query_selector_all: "a", // https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
  // get_attributes: ['href'], // https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
  // link_order: "FIRST_N", // "FIRST_N" or "RANDOM"
  // link_timeout_millis: 30000, // timeout per link
  // max_retries: 0, // number of retries per link if it failed for any reason
  // wait_for_selector: '', // https://pptr.dev/api/puppeteer.page.waitforselector
  // per_link_options: {},
    /*
    // example:
      per_link_options: {
        'http://fake-link1': { expected_status_code: "STATUS_CLASS_4XX" },
        'http://fake-link2': { expected_status_code: 304 },
        'http://fake-link3': { link_timeout_millis: 10000 },
        'http://fake-link4': {
          expected_status_code: "STATUS_CLASS_3XX",
          link_timeout_millis: 10,
        },
      },
    */
  // total_synthetic_timeout_millis: 60000 // Timeout set for the entire Synthetic Monitor
  // screenshot_options: { capture_condition: 'FAILING', storage_location: '' }
};

functions.http('BrokenLinkChecker', GcmSynthetics.runBrokenLinksHandler(options));

後續步驟