寫入和檢視記錄


日誌記錄是調試和監控程式碼的重要工具。 Cloud Functions 讓您可以選擇使用適用於Node.jsPython 的記錄器 SDK,或使用console物件標準進行 Web 開發。

雲端日誌是一項收費服務;如果超出免費配額,您可能需要付費。有關更多信息,請參閱Cloud Logging 定價

寫入日誌

使用 Cloud Functions 記錄器 SDK

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!")

在函數程式碼中對不同類型的日誌使用不同的日誌等級。結構化資料可以作為最後一個參數附加到日誌中。以下是函數如何使用每種日誌類型的範例:

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() ,您可以寫入具有附加日誌嚴重性等級CRITICALALERTEMERGENCY的日誌條目。請參閱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.logconsole.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 控制台中查看函數日誌。

使用 Cloud Logging UI

您可以在 Cloud Logging UI 中查看 Cloud Functions 日誌

分析日誌

Cloud Logging 提供了一套強大的日誌分析工具,您可以使用它們來監控您的 Cloud Functions。

圖表和警報

建立基於日誌的指標來監控功能後,您可以根據這些指標建立圖表和警報。例如,您可以建立一個圖表來視覺化一段時間內的延遲,或建立警報來讓您知道某個錯誤是否經常發生。

有關如何在圖表和警報策略中使用基於日誌的指標的詳細信息,請參閱建立圖表和警報