เขียนและดูบันทึก

การบันทึกเป็นเครื่องมือสำคัญสำหรับการแก้ไขข้อบกพร่องและการตรวจสอบโค้ด Cloud Functions ให้ตัวเลือกในการใช้ SDK ของเครื่องบันทึกสำหรับ Node.js หรือ Python หรือมาตรฐานออบเจ็กต์ console สำหรับการพัฒนาเว็บ

Cloud Logging เป็นบริการที่มีค่าใช้จ่าย คุณอาจถูกเรียกเก็บเงินหากใช้โควต้าแบบไม่มีค่าใช้จ่ายเกิน ดูข้อมูลเพิ่มเติมได้ที่ ราคา Cloud Logging

การเขียนบันทึก

การใช้ SDK ของเครื่องบันทึก Cloud Functions

Cloud Functions SDK ของเครื่องบันทึกจะให้อินเทอร์เฟซมาตรฐาน เพื่อรายงานสถานะจากฟังก์ชันไปยัง Cloud Logging คุณสามารถใช้ SDK นี้เพื่อบันทึกเหตุการณ์ด้วยข้อมูลที่มีโครงสร้าง ซึ่งจะช่วยให้วิเคราะห์และตรวจสอบได้ง่ายขึ้น

นำเข้าจากแพ็กเกจย่อย logger

Node.js

// All available logging functions
const {
  log,
  info,
  debug,
  warn,
  error,
  write,
} = require("firebase-functions/logger");

Python

from firebase_functions import logger
  • คำสั่ง logger.log() มีระดับบันทึก INFO

  • คำสั่ง logger.info() มีระดับบันทึก INFO

  • คำสั่ง logger.warn() มีระดับบันทึก WARNING

  • คำสั่ง logger.error() มีระดับบันทึก ERROR

  • คำสั่ง logger.debug() มีระดับบันทึก DEBUG

  • ข้อความของระบบภายในมีระดับบันทึก DEBUG

ตัวอย่างนี้แสดงฟังก์ชันที่เขียนบันทึกพื้นฐาน

Node.js

exports.helloWorld = onRequest((request, response) => {
  // sends a log to Cloud Logging
  log("Hello logs!");

  response.send("Hello from Firebase!");
});

Python

@https_fn.on_request()
def hello_world(req: https_fn.Request) -> https_fn.Response:
    # sends a log to Cloud Logging
    logger.log("Hello logs!")

    return https_fn.Response("Hello from Firebase!")

ใช้ระดับบันทึกที่แตกต่างกันสำหรับบันทึกประเภทต่างๆ ในโค้ดฟังก์ชัน คุณแนบ Structured Data ไปกับบันทึกเป็นอาร์กิวเมนต์สุดท้ายได้ ต่อไปนี้คือ ตัวอย่างวิธีที่ฟังก์ชันใช้บันทึกแต่ละประเภท

Node.js

exports.getInspirationalQuote = onRequest(async (request, response) => {
  const db = getFirestore();
  const today = new Date();
  const quoteOfTheMonthRef = db
      .collection("quotes")
      .doc(`${today.getFullYear()}`)
      .collection("months")
      .doc(`${today.getMonth()}`);

  const DEFAULT_QUOTE =
      "You miss 100% of the shots you don't take. -Wayne Gretzky";
  let quote;
  try {
    const quoteOfTheMonthDocSnap = await quoteOfTheMonthRef.get();

    // Attach relevant debugging information with debug()
    debug("Monthly quote fetch result", {
      docRef: quoteOfTheMonthRef.path,
      exists: quoteOfTheMonthDocSnap.exists,
      createTime: quoteOfTheMonthDocSnap.createTime,
    });

    if (quoteOfTheMonthDocSnap.exists) {
      quote = quoteOfTheMonthDocSnap.data().text;
    } else {
      // Use warn() for lower-severity issues than error()
      warn("Quote not found for month, sending default instead", {
        docRef: quoteOfTheMonthRef.path,
        dateRequested: today.toLocaleDateString("en-US"),
      });

      quote = DEFAULT_QUOTE;
    }
  } catch (err) {
    // Attach an error object as the second argument
    error("Unable to read quote from Firestore, sending default instead",
        err);

    quote = DEFAULT_QUOTE;
  }

  // Attach relevant structured data to any log
  info("Sending a quote!", {quote: quote});
  response.json({inspirationalQuote: quote});
});

Python

@https_fn.on_request()
def get_inspirational_quote(req: https_fn.Request) -> https_fn.Response:
    firestore_client = firestore.client()
    today = datetime.date.today()
    quote_of_the_month_ref = (firestore_client.collection("quotes").doc(str(
        today.year)).collection("months").doc(str(today.month)))

    default_quote = "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves."

    quote = None
    try:
        quote_of_the_month = quote_of_the_month_ref.get()

        # Attach relevant debugging information with debug()
        logger.debug(
            "Monthly quote fetch result",
            docRef=quote_of_the_month.path,
            exists=quote_of_the_month.exists,
            createTime=quote_of_the_month.createTime,
        )

        if quote_of_the_month.exists:
            quote = quote_of_the_month.to_dict()["text"]
        else:
            # Use warn() for lower-severity issues than error()
            logger.warn(
                "Quote not found for month, sending default instead",
                doc_reference=quote_of_the_month.path,
                date_requested=today.strftime("%Y-%m-%d"),
            )
            quote = default_quote
    except:
        e = sys.exc_info()[0]
        # Attach an error object as the second argument
        logger.error("Unable to read quote from Firestore, sending default instead", error=e)
        quote = default_quote

    # Attach relevant structured data to any log
    logger.info("Sending a quote!", quote=quote)
    return https_fn.Response("Hello from Firebase!")

logger.write() ช่วยให้คุณเขียนรายการบันทึกที่มี ระดับความรุนแรงของบันทึก เพิ่มเติมเป็น CRITICAL, ALERT และ EMERGENCY ได้ ดู LogSeverity

Node.js

exports.appHasARegression = onRegressionAlertPublished((event) => {
  write({
    // write() lets you set additional severity levels
    // beyond the built-in logger functions
    severity: "EMERGENCY",
    message: "Regression in production app",
    issue: event.data.payload.issue,
    lastOccurred: event.data.payload.resolveTime,
  });
});

Python

@crashlytics_fn.on_regression_alert_published()
def app_has_regression(alert: crashlytics_fn.CrashlyticsRegressionAlertEvent) -> None:
    logger.write(
        severity="EMERGENCY",
        message="Regression in production app",
        issue=alert.data.payload.issue,
        last_occurred=alert.data.payload.resolve_time,
    )
    print(alert)

กำลังใช้ console.log

โซลูชันที่แนะนำสำหรับการบันทึกจากฟังก์ชันคือการใช้ SDK ของเครื่องบันทึก สำหรับแพลตฟอร์มของคุณ ใน Node.js คุณสามารถใช้การเรียกการบันทึกมาตรฐานของ JavaScript แทนได้ เช่น console.log และ console.error แต่ก่อนอื่นคุณต้องกำหนดให้โมดูลพิเศษแก้ไขวิธีการมาตรฐานเพื่อให้ทำงานได้อย่างถูกต้อง

require("firebase-functions/logger/compat");

เมื่อมีโมดูลความเข้ากันได้ของเครื่องบันทึกแล้ว คุณจะใช้ console.log() ได้ตามปกติในโค้ด

exports.helloError = functions.https.onRequest((request, response) => {
  console.log('I am a log entry!');
  response.send('Hello World...');
});
  • คำสั่ง console.log() มีระดับบันทึก INFO
  • คำสั่ง console.info() มีระดับบันทึก INFO
  • คำสั่ง console.warn() มีระดับบันทึก ERROR
  • คำสั่ง console.error() มีระดับบันทึก ERROR
  • ข้อความของระบบภายในมีระดับบันทึก DEBUG

การดูบันทึก

คุณดูบันทึกสำหรับ Cloud Functions ได้ในGoogle Cloud คอนโซล Cloud Logging UI หรือผ่านเครื่องมือบรรทัดคำสั่ง firebase

การใช้ Firebase CLI

หากต้องการดูบันทึกด้วยเครื่องมือ firebase ให้ใช้คำสั่ง functions:log ดังนี้

firebase functions:log

หากต้องการดูบันทึกสำหรับฟังก์ชันที่เฉพาะเจาะจง ให้ระบุชื่อฟังก์ชันเป็นอาร์กิวเมนต์

firebase functions:log --only <FUNCTION_NAME>

หากต้องการดูตัวเลือกการดูบันทึกทั้งหมด โปรดดูความช่วยเหลือสำหรับ functions:log

firebase help functions:log

การใช้คอนโซล Google Cloud

คุณดูบันทึกสำหรับฟังก์ชันได้ในGoogle Cloud คอนโซล

การใช้ UI ของ Cloud Logging

คุณดูบันทึกสำหรับ Cloud Functions ได้ใน UI ของ Cloud Logging

การวิเคราะห์บันทึก

Cloud Logging มีชุดเครื่องมือวิเคราะห์บันทึกที่มีประสิทธิภาพซึ่งคุณใช้เพื่อตรวจสอบ Cloud Functions ได้

ชาร์ตเพลงและการแจ้งเตือน

เมื่อสร้างเมตริกตามบันทึกเพื่อตรวจสอบฟังก์ชันแล้ว คุณจะ สร้างแผนภูมิและการแจ้งเตือนตามเมตริกเหล่านี้ได้ เช่น คุณอาจสร้าง แผนภูมิเพื่อแสดงภาพเวลาในการตอบสนองเมื่อเวลาผ่านไป หรือสร้างการแจ้งเตือนเพื่อแจ้งให้คุณทราบ หากเกิดข้อผิดพลาดบางอย่างบ่อยเกินไป

ดูข้อมูลโดยละเอียดเกี่ยวกับวิธีใช้เมตริกตามบันทึกในแผนภูมิและนโยบายการแจ้งเตือนได้ที่การสร้างแผนภูมิและการแจ้งเตือน

ทําความเข้าใจและใช้รหัสการดำเนินการ

โดยค่าเริ่มต้น ฟังก์ชัน Cloud Run (รุ่นที่ 2) รองรับการดำเนินการพร้อมกันของ คำขอหลายรายการภายในอินสแตนซ์ฟังก์ชันเดียว ซึ่งหมายความว่าบันทึกจากคำขอต่างๆ อาจสลับกัน ทำให้ติดตามลำดับการดำเนินการเดียวได้ยากขึ้น

เพื่อช่วยในเรื่องนี้ ฟังก์ชันที่ติดตั้งใช้งานโดยใช้ Firebase CLI เวอร์ชัน 13.33.0 ขึ้นไปจะติดตั้งใช้งานโดยอัตโนมัติพร้อมตัวเลือกในการเชื่อมโยงรหัสการดำเนินการกับรายการบันทึกแต่ละรายการที่ปล่อยออกมาในระหว่างการจัดการการดำเนินการนั้น

รหัสการดำเนินการจะระบุบันทึกทั้งหมดที่เชื่อมโยงกับคำขอเดียวซึ่งฟังก์ชันของคุณจัดการโดยไม่ซ้ำกัน คุณไม่จำเป็นต้องเปลี่ยนแปลงโค้ดใดๆ ระบบจะเพิ่มรหัสการดำเนินการลงในบันทึกโดยอัตโนมัติ

หากต้องการปิดใช้การบันทึกรหัสการดำเนินการในรายการบันทึก ให้ตั้งค่าตัวแปรสภาพแวดล้อม LOG_EXECUTION_ID เป็น false ในไฟล์ dotenv

ค้นหาและเชื่อมโยงบันทึกตามรหัสการดำเนินการ

คุณสามารถตรวจสอบและเชื่อมโยงบันทึกตามรหัสการดำเนินการใน Cloud Logs Explorer

  1. ขยายรายการบันทึกจากฟังก์ชัน รหัสการดำเนินการจะอยู่ใน ข้อมูลบันทึกที่มีโครงสร้าง ซึ่งซ้อนอยู่ภายใต้ป้ายกำกับเป็น labels.execution_id

  2. คลิกค่าของ execution_id แล้วเลือก "แสดงรายการที่ตรงกัน" จาก เมนูแบบเลื่อนลงเพื่อดูบันทึกอื่นๆ ทั้งหมดที่เชื่อมโยงกับการเรียกใช้ฟังก์ชันเดียวกันนั้น

การใช้รหัสการดำเนินการจะช่วยให้คุณจัดกลุ่มข้อความบันทึกทั้งหมดที่เกี่ยวข้องกับคำขอเดียวได้ แม้ว่าฟังก์ชันจะจัดการคำขอหลายรายการพร้อมกันก็ตาม

เพิ่มการมองเห็นบันทึกด้วยช่องสรุปที่กำหนดเอง

หากต้องการให้รหัสการดำเนินการปรากฏใน Logs Explorer ได้ง่ายขึ้น คุณสามารถเพิ่มรหัสดังกล่าวเป็น[ฟิลด์สรุปที่กำหนดเอง][cloud-logging-preference] หลังจากเพิ่มรหัสการดำเนินการเป็นช่องสรุปแล้ว ทุกรายการบันทึกจะแสดงรหัสการดำเนินการเป็นชิปที่จุดเริ่มต้นของบรรทัดบันทึก ซึ่งคล้ายกับวิธีที่ฟังก์ชันรุ่นที่ 1 แสดงรหัสการดำเนินการสำหรับรายการบันทึกทั้งหมด

วิธีเพิ่มรหัสการดำเนินการลงในช่องสรุป

  1. คลิกค่าของรหัสการดำเนินการในรายการบันทึกที่มีโครงสร้างในส่วน labels.execution_id

  2. เลือก "เพิ่มช่องในบรรทัดสรุป" จากเมนูแบบเลื่อนลง

ตอนนี้รายการบันทึกแต่ละรายการจะแสดง executionId อย่างชัดเจนในช่องสรุป เพื่อให้ระบุและจัดกลุ่มบันทึกที่เชื่อมโยงกับรหัสการดำเนินการที่เฉพาะเจาะจงได้ง่ายขึ้น