טריגרים של צד שני עם Cloud Logging

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

הגדרות אישיות

כדי להריץ את הדוגמה במאמר הזה, תצטרכו נושא Pub/Sub ויעד (sink) ב-Cloud Logging. בדוגמה נעשה שימוש ביומנים כדי להעביר יומני ביקורת של Cloud לפונקציית Cloud Run.

מבנה האירוע

בדומה לכל הפונקציות שמופעלות על ידי Pub/Sub, פונקציות שמופעלות על ידי רשומות ביומן של Cloud מקבלות אובייקט PubsubMessage שהפרמטר data שלו הוא מחרוזת עם קידוד base64. באירועים של יומן Cloud, פענוח הערך הזה מחזיר את הרשומה הרלוונטית ביומן כמחרוזת JSON.

קוד לדוגמה

אתם יכולים להשתמש בפונקציה שמופעלת על ידי Pub/Sub כדי לזהות יומני Cloud מיוצאים ולהגיב להם:

Node.js

exports.processLogEntry = data => {
  const dataBuffer = Buffer.from(data.data, 'base64');

  const logEntry = JSON.parse(dataBuffer.toString('ascii')).protoPayload;
  console.log(`Method: ${logEntry.methodName}`);
  console.log(`Resource: ${logEntry.resourceName}`);
  console.log(`Initiator: ${logEntry.authenticationInfo.principalEmail}`);
};

Python

import base64
import json

def process_log_entry(data, context):
    data_buffer = base64.b64decode(data["data"])
    log_entry = json.loads(data_buffer)["protoPayload"]

    print(f"Method: {log_entry['methodName']}")
    print(f"Resource: {log_entry['resourceName']}")
    print(f"Initiator: {log_entry['authenticationInfo']['principalEmail']}")

Go


// Package log contains examples for handling Cloud Functions logs.
package log

import (
	"context"
	"log"
)

// PubSubMessage is the payload of a Pub/Sub event.
// See the documentation for more details:
// https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
type PubSubMessage struct {
	Data []byte `json:"data"`
}

// ProcessLogEntry processes a Pub/Sub message from Cloud Logging.
func ProcessLogEntry(ctx context.Context, m PubSubMessage) error {
	log.Printf("Log entry data: %s", string(m.Data))
	return nil
}

Java


import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import functions.eventpojos.PubsubMessage;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Logger;

public class StackdriverLogging implements BackgroundFunction<PubsubMessage> {
  private static final Logger logger = Logger.getLogger(StackdriverLogging.class.getName());

  @Override
  public void accept(PubsubMessage message, Context context) {
    String name = "World";

    if (!message.getData().isEmpty()) {
      name = new String(Base64.getDecoder().decode(
          message.getData().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
    }
    String res = String.format("Hello, %s", name);
    logger.info(res);
  }
}

פריסת פונקציה

כדי לפרוס את הפונקציה, מריצים את הפקודה הבאה:

Node.js

gcloud functions deploy processLogEntry \
--runtime nodejs22 \
--trigger-topic YOUR_PUBSUB_TOPIC/
FLAGS...

משתמשים בדגל --runtime כדי לציין את מזהה זמן הריצה של גרסת Node.js נתמכת להרצת הפונקציה.

Python

gcloud functions deploy process_log_entry \
--runtime python312 \
--trigger-topic YOUR_PUBSUB_TOPIC/
FLAGS...

משתמשים בדגל --runtime כדי לציין את מזהה זמן הריצה של גרסת Python נתמכת להרצת הפונקציה.

Go

gcloud functions deploy ProcessLogEntry \
--runtime go121 \
--trigger-topic YOUR_PUBSUB_TOPIC/
FLAGS...

כדי לציין את מזהה זמן הריצה של גרסת Go נתמכת להרצת הפונקציה, משתמשים בדגל --runtime.

Java

gcloud functions deploy java-log-function \
--entry-point StackdriverLogging \
--runtime java17 \
--memory 512MB \
--trigger-topic YOUR_PUBSUB_TOPIC/
FLAGS...

משתמשים בדגל --runtime כדי לציין את מזהה זמן הריצה של גרסת Java נתמכת להרצת הפונקציה.

הפעלת פונקציה

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

Method: METHOD
Resource: projects/YOUR_GCLOUD_PROJECT/...
Initiator: YOUR_EMAIL_ADDRESS