כתוב והצג יומנים


רישום הוא כלי חשוב לניפוי באגים ולניטור קוד. Cloud Functions נותן לך את האפשרות להשתמש ב-logger SDK עבור Node.js או Python , או בתקן אובייקט console לפיתוח עבור האינטרנט.

ענן רישום הוא שירות בתשלום; ייתכן שתחויב אם תחרוג מהמכסה ללא עלות. למידע נוסף, ראה תמחור של רישום ענן .

כתיבת יומנים

שימוש ב- Cloud Functions loger SDK

SDK של Cloud Functions loger מספק ממשק סטנדרטי לדיווח על מצב מפונקציות ל-Cloud Logging. אתה יכול להשתמש ב-SDK זה כדי לרשום אירועים עם נתונים מובנים , המאפשרים ניתוח וניטור קלים יותר.

ייבוא ​​מחבילת logger :

Node.js

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

פִּיתוֹן

from firebase_functions import logger
  • לפקודות logger.log() יש את רמת יומן INFO .

  • לפקודות logger.info() יש את רמת יומן INFO .

  • לפקודות logger.warn() יש את רמת יומן האזהרה .

  • לפקודות 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!");
});

פִּיתוֹן

@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});
});

פִּיתוֹן

@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,
  });
});

פִּיתוֹן

@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

הפתרון המומלץ לרישום מפונקציה הוא להשתמש ב-logger 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 .

צפייה ביומנים

יומנים עבור פונקציות ענן ניתנות לצפייה במסוף Google Cloud , ממשק המשתמש של Cloud Logging או באמצעות כלי שורת הפקודה 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.

ניתוח יומנים

Cloud Logging מציע חבילה רבת עוצמה של כלים לניתוח יומנים שבהם אתה יכול להשתמש כדי לנטר את פונקציות הענן שלך.

תרשימים והתראות

לאחר שיצרת מדדים מבוססי יומנים כדי לנטר את הפונקציות שלך, תוכל ליצור תרשימים והתראות על סמך מדדים אלה. לדוגמה, תוכל ליצור תרשים כדי להמחיש את זמן האחזור לאורך זמן, או ליצור התראה כדי ליידע אותך אם שגיאה מסוימת מתרחשת לעתים קרובות מדי.

ראה יצירת תרשימים והתראות למידע מפורט על אופן השימוש במדדים מבוססי יומנים בתרשימים ובמדיניות התראות.