הטמעה של webhooks

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

הגדרת פרמטר של סשן

בדוגמאות הבאות אפשר לראות איך מגדירים פרמטר של סשן.

Go

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

כדאי לעיין במדריך למתחילים בנושא Webhooks.

Java

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


// TODO: Change class name to Example
// TODO: Uncomment the line below before running cloud function
// package com.example;

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import java.io.BufferedWriter;

public class WebhookConfigureSessionParameters implements HttpFunction {
  @Override
  public void service(HttpRequest request, HttpResponse response) throws Exception {
    JsonObject orderParameter = new JsonObject();
    orderParameter.addProperty("order_number", "12345");

    JsonObject parameterObject = new JsonObject();
    parameterObject.add("parameters", orderParameter);

    // Creates webhook response object
    JsonObject webhookResponse = new JsonObject();
    webhookResponse.add("session_info", parameterObject);

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String jsonResponseObject = gson.toJson(webhookResponse);

    /** { "session_info": { "parameters": { "order_number": "12345" } } } */
    BufferedWriter writer = response.getWriter();
    // Sends the webhookResponseObject
    writer.write(jsonResponseObject.toString());
  }
}

Node.js

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

const functions = require('@google-cloud/functions-framework');

functions.http('configureSessionParams', (request, response) => {
  // Session parameter configured by the webhook
  const orderNumber = 123;

  const jsonResponse = {
    sessionInfo: {
      parameters: {
        orderNumber: orderNumber,
      },
    },
  };

  response.send(jsonResponse);
});

Python

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import functions_framework

# TODO (developer): change entry point to configure_session_params in Cloud Function


@functions_framework.http
def configure_session_params(request):
    """Webhook to validate or configure new session parameters."""

    order_number = 123

    json_response = {
        "sessionInfo": {
            "parameters": {
                "orderNumber": order_number,
            },
        },
    }

    return json_response

החזרת תגובה על מילוי הזמנה

בדוגמאות הבאות אפשר לראות איך להחזיר תגובה לביצוע הזמנה.

Go

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

כדאי לעיין במדריך למתחילים בנושא Webhooks.

Java

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


// TODO: Change class name to Example
// TODO: add GSON dependency to Pom file
// (https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.5)
// TODO: Uncomment the line bellow before running cloud function
// package com.example;

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedWriter;

public class BasicWebhook implements HttpFunction {
  @Override
  public void service(HttpRequest request, HttpResponse response) throws Exception {
    Gson gson = new GsonBuilder().create();
    JsonObject parsedRequest = gson.fromJson(request.getReader(), JsonObject.class);

    // For more information on the structure of this object https://cloud.google.com/dialogflow/cx/docs/reference/rest/v3/Fulfillment
    String requestTag = parsedRequest.getAsJsonObject("fulfillmentInfo")
        .getAsJsonPrimitive("tag").toString();
    JsonObject responseObject = null;
    String defaultIntent = "\"Default Welcome Intent\"";
    String secondIntent = "\"get-agent-name\"";
    String responseText = "";

    // Compares the Intent Tag to provide the correct response 
    if (requestTag.equals(defaultIntent)) {
      responseText = "\"Hello from a Java GCF Webhook\"";
    } else if (requestTag.equals(secondIntent)) {
      responseText = "\"My name is Flowhook\"";
    } else {
      responseText = "\"Sorry I didn't get that\"";
    }

    // Constructing the response jsonObject 
    responseObject =
        JsonParser
            .parseString(
                "{ \"fulfillment_response\": { \"messages\": [ { \"text\": { \"text\": ["
                    + responseText
                    + "] } } ] } }")
            .getAsJsonObject();
    BufferedWriter writer = response.getWriter();

    //Sends the responseObject
    writer.write(responseObject.toString());
  }
}

Node.js

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

const functions = require('@google-cloud/functions-framework');

functions.http('handleWebhook', (request, response) => {
  const tag = request.body.fulfillmentInfo.tag;
  let text = '';

  if (tag === 'Default Welcome Intent') {
    text = 'Hello from a GCF Webhook';
  } else if (tag === 'get-name') {
    text = 'My name is Flowhook';
  } else {
    text = `There are no fulfillment responses defined for "${tag}"" tag`;
  }

  const jsonResponse = {
    fulfillment_response: {
      messages: [
        {
          text: {
            //fulfillment text response to be sent to the agent
            text: [text],
          },
        },
      ],
    },
  };

  response.send(jsonResponse);
});

Python

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import functions_framework

# TODO(developer): change entry point to handle_webhook in cloud function


@functions_framework.http
def handle_webhook(request):
    req = request.get_json()

    tag = req["fulfillmentInfo"]["tag"]

    if tag == "Default Welcome Intent":
        text = "Hello from a GCF Webhook"
    elif tag == "get-name":
        text = "My name is Flowhook"
    else:
        text = f"There are no fulfillment responses defined for {tag} tag"

    # You can also use the google.cloud.dialogflowcx_v3.types.WebhookRequest protos instead of manually writing the json object
    # Please see https://googleapis.dev/python/dialogflow/latest/dialogflow_v2/types.html?highlight=webhookresponse#google.cloud.dialogflow_v2.types.WebhookResponse for an overview
    res = {"fulfillment_response": {"messages": [{"text": {"text": [text]}}]}}

    # Returns json
    return res

הגדרת פרמטרים בטופס לפי הצורך

בדוגמאות הבאות אפשר לראות איך מסמנים פרמטר כפרמטר חובה.

Java

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


// TODO: Change class name to Example
// TODO: Uncomment the line below before running cloud function
// package com.example;

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.BufferedWriter;

public class ConfigureWebhookToSetFormParametersAsOptionalOrRequired implements HttpFunction {
  @Override
  public void service(HttpRequest request, HttpResponse response) throws Exception {
    JsonObject parameterObject = new JsonObject();
    parameterObject.addProperty("display_name", "order_number");
    parameterObject.addProperty("required", "true");
    parameterObject.addProperty("state", "VALID");

    JsonArray parameterInfoList = new JsonArray();
    parameterInfoList.add(parameterObject);

    JsonObject parameterInfoObject = new JsonObject();
    parameterInfoObject.add("parameter_info", parameterInfoList);

    JsonObject formInfo = new JsonObject();
    formInfo.add("form_info", parameterInfoObject);

    // Constructs the webhook response object
    JsonObject webhookResponse = new JsonObject();
    webhookResponse.add("page_info", formInfo);

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String jsonResponseObject = gson.toJson(webhookResponse);

    /* {
     *   "page_info": {
     *     "form_info": {
     *       "parameter_info": [
     *         {
     *           "display_name": "order_number",
     *           "required": "true",
     *           "state": "VALID"
     *         }
     *       ]
     *     }
     *   }
     * }
     */

    BufferedWriter writer = response.getWriter();

    // Sends the responseObject
    writer.write(jsonResponseObject.toString());
  }
}

Node.js

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

const functions = require('@google-cloud/functions-framework');

functions.http('configureOptionalFormParam', (request, response) => {
  // The value of the parameter that the webhook will set as optional or required.
  // Note that the webhook cannot add or remove any form parameter

  const jsonResponse = {
    pageInfo: {
      formInfo: {
        parameterInfo: [
          {
            displayName: 'order-number',
            // if required: false, the agent will not reprompt for this parameter, even if the state is 'INVALID'
            required: true,
            state: 'VALID',
          },
        ],
      },
    },
  };

  // Info about form parameter that is sent in the webhook response:
  console.log(
    'Parameter Info: \n',
    jsonResponse.pageInfo.formInfo.parameterInfo[0]
  );

  response.send(jsonResponse);
});

אימות של פרמטר בטופס

בדוגמאות הבאות אפשר לראות איך מאמתים פרמטר של טופס.

Java

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


// TODO: Change class name to Example
// TODO: Uncomment the line below before running cloud function
// package com.example;

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.BufferedWriter;

public class WebhookValidateFormParameter implements HttpFunction {
  @Override
  public void service(HttpRequest request, HttpResponse response) throws Exception {
    JsonObject sessionInfo = new JsonObject();
    JsonObject sessionParameter = new JsonObject();

    sessionParameter.addProperty("order_number", "null");
    sessionInfo.add("parameters", sessionParameter);

    JsonObject parameterObject = new JsonObject();
    parameterObject.addProperty("display_name", "order_number");
    parameterObject.addProperty("required", "true");
    parameterObject.addProperty("state", "INVALID");
    parameterObject.addProperty("value", "123");

    JsonArray parameterInfoList = new JsonArray();
    parameterInfoList.add(parameterObject);

    JsonObject parameterInfoObject = new JsonObject();
    parameterInfoObject.add("parameter_info", parameterInfoList);

    JsonObject pageInfo = new JsonObject();
    pageInfo.add("form_info", parameterInfoObject);

    // Constructs the webhook response object
    JsonObject webhookResponse = new JsonObject();
    webhookResponse.add("page_info", pageInfo);
    webhookResponse.add("session_info", sessionInfo);

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String jsonResponseObject = gson.toJson(webhookResponse);

    /**
     * { "page_info": { "form_info": { "parameter_info": [ { "display_name": "order_number",
     * "required": "true", "state": "INVALID", "value": "123" } ] } }, "session_info": {
     * "parameters": { "order_number": "null" } } }
     */
    BufferedWriter writer = response.getWriter();

    // Sends the responseObject
    writer.write(jsonResponseObject.toString());
  }
}

Node.js

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

const functions = require('@google-cloud/functions-framework');

functions.http('validateParameter', (request, response) => {
  // Webhook will validate or invalidate parameter based on logic configured by the user.
  // Access parameter values through the webhook request via `request.body.pageInfo.formInfo.parameterInfo[]`
  const jsonResponse = {
    page_info: {
      form_info: {
        parameter_info: [
          {
            displayName: 'orderNumber',
            required: true,
            state: 'INVALID',
            value: 123,
          },
        ],
      },
    },
    sessionInfo: {
      parameters: {
        // Set session parameter to null if the form parameter is 'INVALID' and your agent needs to reprompt the user
        orderNumber: null,
      },
    },
  };

  response.send(jsonResponse);
});

Python

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import functions_framework


@functions_framework.http
def validate_parameter(request):
    """Webhook will validate or invalidate parameter based on logic configured by the user."""
    return {
        "page_info": {
            "form_info": {
                "parameter_info": [
                    {
                        "displayName": "orderNumber",
                        "required": True,
                        "state": "INVALID",
                        "value": 123,
                    },
                ],
            },
        },
        "sessionInfo": {
            "parameters": {
                # Set session parameter to None if the form parameter is 'INVALID' and your agent needs to reprompt the user
                "orderNumber": None,
            },
        },
    }

מזהה סשן ביומן

בדוגמה הבאה אפשר לראות איך מתעדים את session ID מבקשת webhook.

Python

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import re

import functions_framework


@functions_framework.http
def log_session_id_for_troubleshooting(request):
    """Webhook will log session id corresponding to request."""

    req = request.get_json()
    # You can read more about SessionInfo at https://cloud.google.com/dialogflow/cx/docs/reference/rest/v3/SessionInfo
    # Use a regex pattern to get the session ID
    session_id_regex = r".+\/sessions\/(.+)"
    session = req["sessionInfo"]["session"]
    regex_match = re.search(session_id_regex, session)
    session_id = regex_match.group(1)

    # Instead of printing, use the logging tools available to you
    print(f"Debug Node: session ID = {session_id}")

    # Return a generic response
    res = {
        "fulfillment_response": {
            "messages": [{"text": {"text": [f"Request Session ID: {session_id}"]}}]
        }
    }

    # Returns json
    return res

פתרון בעיות

תוקף שיחת webhook

קריאות ל-Webhook תמיד מתבצעות על ידי Dialogflow CX ועוברות לשרת אינטרנט באמצעות HTTPS. קריאות webhook של שירות אינטרנט גנרי מגיעות מכתובת IP באינטרנט ששייכת ל-Google ויכולות להגיע לשרתי אינטרנט (שרתי webhook) שזמינים באינטרנט הציבורי. לעומת זאת, וווב-הוקים של Service Directory תמיד מתחילים מכתובת פנימיתGoogle Cloud ויכולים להגיע רק לשרתי וווב-הוק ברשתות פרטיות בתוך Google Cloud.

יומנים שימושיים לניפוי באגים של ווּבּהוּקים

בדרך כלל, כדי לנפות באגים ב-webhook, צריך לאסוף את היומנים של Dialogflow CX ב-Cloud Logging ואת היומנים של שרת ה-webhook. אם שרת ה-webhook מיושם באמצעות פונקציות Cloud Run, היומנים שלו יהיו ב-Cloud Logging. אחרת, בדרך כלל היומנים נמצאים במקום שבו שרת ה-webhook פועל.

יומני webhook רגילים מכילים שדה detectIntentResponseId עם UUID שיכול להיות שימושי למעקב אחרי שיחה מסוימת בשרתי webhook. היומן הזה קיים ביומנים של Cloud Logging ב-Dialogflow CX כש-Cloud Logging מופעל.

בעיות נפוצות שקשורות לתגובה לפעולה מאתר אחר (webhook)

אלה כמה מהשגיאות שאפשר למצוא ביומני Dialogflow CX לגבי קריאות ל-webhook:

שגיאה בפענוח שם המארח של שרת ה-webhook

מערכת Dialogflow CX חיפשה את שם המארח של webhook כללי, ושם המארח לא קיים ב-DNS. מוודאים ששם המארח רשום ב-DNS הציבורי. אם שם המארח חדש, יכול להיות שיעבור זמן עד שהרשומה תתעדכן. הודעה מ-Cloud Logging: State: URL_ERROR, Reason: ERROR_DNS.

השרת של ה-webhook מחזיר שגיאה בצד הלקוח

מלבד ERROR_DNS, המצב הזה מציין תגובה מסוג 4xx משרת ה-webhook. יכול להיות שזה סטטוס לא מורשה (401 – ERROR_AUTHENTICATION) או שכתובת ה-URL לא נמצאה בשרת של ה-webhook (404 – ERROR_NOT_FOUND). הודעה ב-Cloud Logging: State: URL_ERROR.

הזמן הקצוב לתגובה של סוכן Dialogflow מסתיים לפני ששרת ה-webhook מחזיר תשובה

הגענו למגבלת הזמן הקצוב לתפוגה של ה-webhook ב-Dialogflow CX לפני שהשרת סיים את הפעולה. יש שתי גישות אפשריות: קיצור זמן העיבוד של שרת ה-webhook או הגדלת הזמן שבו Dialogflow CX מחכה ל-webhook. קיצור זמן העיבוד בדרך כלל מניב את התוצאות הטובות ביותר, אבל במקרים רבים זה לא פשוט. חשוב לזכור שיש מגבלת זמן קצובה מקסימלית ל-webhook, ומשתמשי הקצה או המתקשרים יצטרכו להמתין זמן רב יותר כדי לקבל תשובה מהנציג לפני שמגדילים את ההגדרה הזו. Cloud Logging message: State: URL_TIMEOUT, Reason: TIMEOUT_WEB.

הזמן הקצוב לתפוגה של gRPC מסתיים לפני ששרת ה-webhook מחזיר תגובה

הגענו למגבלת הזמן שהוגדרה על ידי gRPC בקריאה ל-API של Dialogflow CX לפני שהסתיימה קריאת ה-webhook. המגבלה הזו מוגדרת בדרך כלל ברמת השילוב, והיא לא קשורה לפרמטרים של Dialogflow CX ולמגבלות הזמן הקצוב לתפוגה של ה-webhook. מידע נוסף על מועדים סופיים ב-gRPC זמין בכתובת https://grpc.io/docs/guides/deadlines/. Cloud Logging message: State: URL_REJECTED, Reason: REJECTED_DEADLINE_EXCEEDED.

ל-Dialogflow לא הייתה אפשרות ליצור קשר עם שרת ה-webhook

לא הייתה אפשרות להגיע לשרת ה-webhook בגלל שגיאה בחיבור לרשת, או שהחיבור נוצר והשרת החזיר סטטוס HTTP 5xx, שמציין בעיה במהלך עיבוד הבקשה. מוודאים ש-Dialogflow CX יכול לגשת לכתובת שרת ה-webhook ברמת הרשת. אם הבקשה מופיעה ביומני השרת של ה-webhook, צריך לבדוק למה הקריאה החזירה שגיאת 5xx. הודעה מ-Cloud Logging:‏ State: URL_UNREACHABLE.

מעקב אחר שיחות webhook

אפשר לבצע קורלציה בין קריאה רגילה ל-webhook לבין שרת webhook באמצעות מזהה הסשן, מזהה detectIntentResponse, מזהה המעקב של פונקציות Cloud Run וחותמת הזמן של הקריאה. אפשר לבצע מעקב גמיש אחרי webhook באמצעות חותמת הזמן של הקריאה וערכי הפרמטר של הסשן שצוינו בהגדרת ה-webhook בזמן העיצוב. מידע נוסף על בקשות סטנדרטיות וגמישות של Webhook זמין במאמר בנושא Webhooks.

מזהה הסשן מופיע בשדה sessionInfo.session של WebhookRequest. מזהה הסשן הזה צריך להיות ייחודי לכל שיחה, והוא יכול לעזור לכם להשוות בין יומני נציגים לבין יומני webhook לבקשות שמשתמשות באותו מזהה סשן. בקטע הקודם Log session ID מוסבר איך לרשום את מזהה הסשן מ-webhook.

בנוסף, אם אתם מארחים את ה-webhook בפונקציות Cloud Run או באפשרות דומה של Google Cloud שרתים וירטואליים, אתם יכולים להשתמש בשדה trace מרשומות היומן כמסנן יומן. ביצוע יחיד של פונקציה יוצר כמה רשומות ביומן עם אותו ערך של מעקב.

בדוגמה הבאה נעשה שימוש גם במזהה הסשן וגם בערך המעקב כדי לשייך יומן שגיאות מסוים של סוכן Dialogflow CX לרשומות המתאימות ביומן של webhook של פונקציות Cloud Run. בדוגמה נעשה שימוש במסננים של Cloud Logging עבור סוכן שמופעל בו Cloud Logging.

1. סינון יומנים של Dialogflow CX לפי יומני שגיאות של סוכן מסוים

כדי לסנן את יומני Dialogflow CX לפי יומני שגיאות של סוכן מסוים, משתמשים במסנן Cloud Logging הבא:

labels.location_id="global"
labels.agent_id="AGENT_ID"
severity=ERROR

רשומה של שגיאה ביומן של webhook נראית כך:

{
  "insertId": "-j4gkkre31e2o",
  "jsonPayload": {
    "code": 14,
    "message": "Error calling webhook 'https://us-central1-PROJECT_ID.cloudfunctions.net/function-webhook': State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500"
  },
  "labels": {
    "agent_id": "e9e01392-1351-42dc-9b15-b583fb2d2881",
    "environment_id": "",
    "location_id": "global",
    "session_id": "07c899-a86-78b-a77-569625b37"
  },
  "logName": "projects/PROJECT_ID/logs/dialogflow-runtime.googleapis.com%2Frequests",
  "receiveTimestamp": "2024-10-28T21:49:04.288439054Z",
  "resource": {
    "labels": {
      "project_id": "PROJECT_ID"
    },
    "type": "global",
  },
  "severity": "ERROR",
  "timestamp": "2024-10-28T21:49:04.132548Z"
}

שימו לב לשדה labels.session_id שמכיל את מזהה הסשן. תשתמשו במזהה הסשן בשלב הבא.

2. סינון יומני רישום של פונקציות Cloud Run לפי מזהה סשן

כדי לסנן את היומנים של פונקציות Cloud Run לפי מזהה סשן, משתמשים במסנן Cloud Logging הבא:

resource.type = "cloud_run_revision"
resource.labels.service_name = "CLOUD_RUN_FUNCTION_NAME"
resource.labels.location = "CLOUD_RUN_FUNCTION_REGION"
textPayload="Debug Node: session ID = SESSION_ID"

היומנים שמתקבלים תואמים ליומני ה-webhook שנוצרו במהלך הסשן שצוין. לדוגמה:

{
  "insertId": "671c42940007ebebdbb1d56e",
  "labels": {
    "execution_id": "pgy8jvvblovs",
    "goog-managed-by": "cloudfunctions",
    "instance_id": "004940b3b8e3d975a4b11a4ed7d1ded4ce3ed37467ffc5e2a8f13a1908db928f8200b01cc554a5eda66ffc9d23d76dd75cec1619a07cb5751fa2e8a93bc6cfc3df86dfa0650a"
  },
  "logName": "projects/PROJECT_ID/logs/run.googleapis.com%2Fstdout",
  "receiveTimestamp": "2024-10-26T01:15:00.523313187Z",
  "resource": {
    "labels": {
      "configuration_name": "function-webhook",
      "location": "us-central1",
      "project_id": "PROJECT_ID",
      "revision_name": "function-webhook-00001-jiv",
      "service_name": "function-webhook",
    },
    "type": "cloud_run_revision"
  },
  "spanId": "6938366936362981595",
  "trace": "d1b54fbc8945dd59bdcaed37d7d5e185",
  "textPayload": "Debug Node: session ID = 07c899-a86-78b-a77-569625b37",
  "timestamp": "2024-10-26T01:15:00.519147Z"
}

שימו לב לשדה trace שבו תשתמשו בשלב הבא.

3. סינון יומנים של Cloud Functions לפי מעקב מסוים

כדי לסנן את היומנים של Cloud Functions לפי מעקב מסוים, משתמשים במסנן Cloud Logging הבא:

resource.type = "cloud_run_revision"
resource.labels.service_name = "CLOUD_RUN_FUNCTION_NAME"
resource.labels.location = "CLOUD_RUN_FUNCTION_REGION"
trace="projects/PROJECT_ID/traces/TRACE_ID"

כאשר TRACE_ID הוא הקטע האחרון של ה-trace. לדוגמה, TRACE_ID של projects/PROJECT_ID/traces/e41eefc1fac48665b442bfa400cc2f5e הוא e41eefc1fac48665b442bfa400cc2f5e.

התוצאה היא יומן השרת של ה-webhook שנוצר במהלך הביצוע של בקשת ה-webhook שמשויכת למזהה הסשן משלב 1 ולמעקב משלב 2. היומן ייראה כך:

{
  "insertId": "671c42940008465e29f5faf0",
  "httpRequest": {
    "requestMethod": "POST",
    "requestUrl": "https://us-central1-TEST_PROJECT.cloudfunctions.net/function-webhook",
    "requestSize": "2410",
    "status": 200,
    "responseSize": "263",
    "userAgent": "Google-Dialogflow",
    "remoteIp": "8.34.210.1",
    "serverIp": "216.239.36.1",
    "latency": "0.166482342s",
    "protocol": "HTTP/1.1"
  },
  "resource": {
    "type": "cloud_run_revision",
    "labels": {
      "project_id": "PROJECT_ID",
      "service_name": "function-webhook",
      "location": "us-central1",
      "revision_name": "function-webhook-00001-jiv",
      "configuration_name": "function-webhook"
    }
  },
  "timestamp": "2024-10-26T01:15:00.352197Z",
  "severity": "INFO",
  "labels": {
    "instanceId": "004940b3b813af8a656c92aac1bd07ffad5165f1353e1e346b6161c14bcde225f68f4a88ceedc08aa9020f387b1b59471f73de45f2882a710ced37dea921f05ad962347690be",
    "goog-managed-by": "cloudfunctions"
  },
  "logName": "projects/test-project-12837/logs/run.googleapis.com%2Frequests",
  "trace": "projects/test-project-12837/traces/d1b54fbc8945dd59bdcaed37d7d5e185",
  "receiveTimestamp": "2024-10-26T01:15:00.548931586Z",
  "spanId": "604a07f7b33b18db",
  "traceSampled": true
}