كتابة السجلات وعرضها


يعد التسجيل أداة مهمة لتصحيح الأخطاء ومراقبة التعليمات البرمجية. تمنحك Cloud Functions خيار استخدام أداة تسجيل SDK لـ Node.js أو Python ، أو معيار كائن وحدة console للتطوير للويب.

التسجيل السحابي هو خدمة مدفوعة؛ قد تتم محاسبتك إذا تجاوزت الحصة بدون تكلفة. لمزيد من المعلومات، راجع تسعير التسجيل السحابي .

كتابة السجلات

استخدام SDK مسجل وظائف السحابة

يوفر Cloud Functions logger SDK واجهة قياسية للإبلاغ عن الحالة من الوظائف إلى 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() لها مستوى سجل الخطأ .

  • أوامر 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 . راجع خطورة السجل .

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

الحل الموصى به للتسجيل من إحدى الوظائف هو استخدام أداة تسجيل 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() على مستوى سجل الأخطاء .
  • تحتوي أوامر console.error() على مستوى سجل الأخطاء .
  • تحتوي رسائل النظام الداخلية على مستوى سجل DEBUG .

عرض السجلات

يمكن عرض سجلات وظائف السحابة إما في وحدة تحكم 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 مجموعة قوية من أدوات تحليل السجلات التي يمكنك استخدامها لمراقبة وظائف السحابة الخاصة بك.

الرسوم البيانية والتنبيهات

بمجرد إنشاء مقاييس قائمة على السجلات لمراقبة وظائفك، يمكنك إنشاء مخططات وتنبيهات بناءً على هذه المقاييس. على سبيل المثال، يمكنك إنشاء مخطط لتصور زمن الاستجابة بمرور الوقت، أو إنشاء تنبيه لإعلامك في حالة حدوث خطأ معين بشكل متكرر.

راجع إنشاء المخططات والتنبيهات للحصول على معلومات تفصيلية حول كيفية استخدام المقاييس المستندة إلى السجلات في المخططات وسياسات التنبيه.