Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Banyak Google Cloud peristiwa yang dicatat ke dalam log di Cloud Audit Logs. Anda dapat
memfilter log ini dan meneruskannya ke topik Pub/Sub menggunakan
sink. Topik Pub/Sub ini selanjutnya dapat mengirimkan notifikasi yang memicu fungsi Cloud Run. Anda dapat
membuat peristiwa kustom dari layanan Google Cloud mana pun yang menghasilkan
log audit.
Halaman ini menunjukkan contoh cara memicu fungsi dari entri log yang dirutekan ke topik Pub/Sub.
Struktur peristiwa fungsi yang dipicu Pub/Sub
Seperti semua fungsi yang dipicu Pub/Sub, fungsi yang dipicu oleh entri log Cloud Logging menerima objek PubsubMessage yang parameter data-nya adalah string berenkode base64. Untuk peristiwa log Cloud Logging, mendekode nilai ini akan menampilkan entri log yang relevan sebagai string JSON.
Sebelum memulai
Kode contoh meneruskan Cloud Audit Logs ke fungsi Cloud Run.
Sebelum menjalankan contoh kode, Anda akan memerlukan hal berikut:
// Package log contains examples for handling Cloud Functions logs.packagelogimport("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/PubsubMessagetypePubSubMessagestruct{Data[]byte`json:"data"`}// ProcessLogEntry processes a Pub/Sub message from Cloud Logging.funcProcessLogEntry(ctxcontext.Context,mPubSubMessage)error{log.Printf("Log entry data: %s",string(m.Data))returnnil}
Untuk mengonfigurasi pemicu selama deployment fungsi:
Jalankan perintah berikut di direktori yang berisi kode contoh
untuk men-deploy fungsi Anda:
Node.js
gcloud run deploy nodejs-log-function \
--source . \
--function processLogEntry \
--base-image nodejs20 \
--region REGION
Python
gcloud run deploy python-log-function \
--source . \
--function process_log_entry \
--base-image python312 \
--region REGION
Go
gcloud run deploy go-log-function \
--source . \
--function ProcessLogEntry \
--base-image go122 \
--region REGION
Java
gcloud run deploy java-log-function \
--source . \
--function StackdriverLogging \
--base-image java21 \
--region REGION
Ganti:
REGION dengan Google Cloud
region tempat Anda ingin men-deploy
fungsi Anda. Contohnya, europe-west1
Flag --function menentukan titik entri ke fungsi dalam
kode sumber contoh. Ini adalah kode yang dijalankan Cloud Run saat fungsi Anda berjalan. Nilai flag ini harus berupa nama fungsi atau
nama class yang sepenuhnya memenuhi syarat yang ada dalam kode sumber Anda.
Flag --base-image menentukan lingkungan image dasar untuk fungsi Anda. Untuk mengetahui detail selengkapnya tentang image dasar dan paket yang disertakan dalam setiap image, lihat Image dasar runtime.
Jalankan perintah berikut untuk membuat pemicu yang memfilter peristiwa:
EVENTARC_TRIGGER_LOCATION dengan lokasi untuk
pemicu Eventarc. Secara umum, lokasi pemicu Eventarc harus cocok dengan lokasi resource Google Cloud yang ingin Anda pantau peristiwanya. Dalam sebagian besar skenario, Anda juga harus men-deploy fungsi di region yang sama. Lihat Memahami lokasi Eventarc untuk mengetahui detail selengkapnya tentang lokasi pemicu Eventarc.
PROJECT_NUMBER dengan Google Cloud nomor project Anda. Pemicu Eventarc ditautkan ke akun layanan untuk digunakan
sebagai identitas saat memanggil fungsi Anda. Akun layanan pemicu Eventarc Anda harus memiliki izin untuk memanggil fungsi Anda. Secara
default, Cloud Run menggunakan Akun layanan komputasi default.
Flag --event-filters menentukan filter peristiwa yang dipantau pemicu. Peristiwa yang cocok dengan semua event-filters, filter
memicu panggilan ke fungsi Anda. Setiap pemicu harus memiliki
jenis peristiwa yang didukung. Anda tidak dapat mengubah jenis filter peristiwa setelah dibuat. Untuk mengubah jenis filter peristiwa, Anda harus membuat pemicu baru dan menghapus pemicu lama. Secara opsional,
Anda dapat mengulangi tanda --event-filters dengan filter yang didukung dalam
bentuk ATTRIBUTE=VALUE untuk menambahkan lebih banyak filter.
Entri log cloud
Saat entri log Cloud yang cocok dengan salah satu filter Anda dibuat, entri log yang sesuai untuk fungsi Anda di konsol Google Cloud akan terlihat seperti berikut:
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-09-02 UTC."],[],[],null,["# Trigger functions from log entries\n\n[Many Google Cloud events](/logging/docs/audit/services) are logged in Cloud Audit Logs. You can\nfilter these logs and forward them to Pub/Sub topics using\n[sinks](/logging/docs/export). These Pub/Sub topics can then send notifications\nthat [trigger](/run/docs/triggering/pubsub-triggers) Cloud Run functions. You can\ncreate custom events from any Google Cloud service that produces\n[audit logs](/logging/docs/audit/services).\n\nThis page shows an example of how to trigger functions from log entries routed\nto a Pub/Sub topic.\n\nEvent structure of Pub/Sub-triggered functions\n----------------------------------------------\n\nLike all [Pub/Sub-triggered functions](/run/docs/triggering/pubsub-triggers), functions\ntriggered by Cloud Logging log entries receive a\n[`PubsubMessage`](/pubsub/docs/reference/rest/v1/PubsubMessage) object whose `data` parameter is a\n`base64`-encoded string. For Cloud Logging log events, decoding this value\nreturns the relevant log entry as a JSON string.\n\nBefore you begin\n----------------\n\nThe sample code forwards Cloud Audit Logs to a Cloud Run function.\nBefore you run the sample code, you'll need the following:\n\n- [Pub/Sub topic](/pubsub/docs/create-topic-console#create_a_topic)\n- [Cloud Logging sink](/logging/docs/export/configure_export_v2#dest-create)\n\nSee the [Pub/Sub triggers guide](/run/docs/triggering/pubsub-triggers) for the APIs to enable\nand the required roles for deploying functions that are triggered by\nPub/Sub.\n\nSample code\n-----------\n\nYou can use a [Pub/Sub-triggered function](/run/docs/triggering/pubsub-triggers) to detect and\nrespond to exported Cloud Logging logs: \n\n### Node.js\n\n exports.processLogEntry = data =\u003e {\n const dataBuffer = Buffer.from(data.data, 'base64');\n\n const logEntry = JSON.parse(dataBuffer.toString('ascii')).protoPayload;\n console.log(`Method: ${logEntry.methodName}`);\n console.log(`Resource: ${logEntry.resourceName}`);\n console.log(`Initiator: ${logEntry.authenticationInfo.principalEmail}`);\n };\n\n### Python\n\n import base64\n import json\n\n def process_log_entry(data, context):\n data_buffer = base64.b64decode(data[\"data\"])\n log_entry = json.loads(data_buffer)[\"protoPayload\"]\n\n print(f\"Method: {log_entry['methodName']}\")\n print(f\"Resource: {log_entry['resourceName']}\")\n print(f\"Initiator: {log_entry['authenticationInfo']['principalEmail']}\")\n\n### Go\n\n\n // Package log contains examples for handling Cloud Functions logs.\n package log\n\n import (\n \t\"context\"\n \t\"log\"\n )\n\n // PubSubMessage is the payload of a Pub/Sub event.\n // See the documentation for more details:\n // https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage\n type PubSubMessage struct {\n \tData []byte `json:\"data\"`\n }\n\n // ProcessLogEntry processes a Pub/Sub message from Cloud Logging.\n func ProcessLogEntry(ctx context.Context, m PubSubMessage) error {\n \tlog.Printf(\"Log entry data: %s\", string(m.Data))\n \treturn nil\n }\n\n### Java\n\n\n import com.google.cloud.functions.BackgroundFunction;\n import com.google.cloud.functions.Context;\n import functions.eventpojos.PubsubMessage;\n import java.nio.charset.StandardCharsets;\n import java.util.Base64;\n import java.util.logging.Logger;\n\n public class StackdriverLogging implements BackgroundFunction\u003cPubsubMessage\u003e {\n private static final Logger logger = Logger.getLogger(StackdriverLogging.class.getName());\n\n @Override\n public void accept(PubsubMessage message, Context context) {\n String name = \"World\";\n\n if (!message.getData().isEmpty()) {\n name = new String(Base64.getDecoder().decode(\n message.getData().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);\n }\n String res = String.format(\"Hello, %s\", name);\n logger.info(res);\n }\n }\n\nDeploy and trigger a function\n-----------------------------\n\nTo configure a trigger during function deployment:\n\n1. Run the following command in the directory that contains the sample code\n to deploy your function:\n\n ### Node.js\n\n gcloud run deploy nodejs-log-function \\\n --source . \\\n --function processLogEntry \\\n --base-image nodejs20 \\\n --region \u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e\n\n ### Python\n\n gcloud run deploy python-log-function \\\n --source . \\\n --function process_log_entry \\\n --base-image python312 \\\n --region \u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e\n\n ### Go\n\n gcloud run deploy go-log-function \\\n --source . \\\n --function ProcessLogEntry \\\n --base-image go122 \\\n --region \u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e\n\n ### Java\n\n gcloud run deploy java-log-function \\\n --source . \\\n --function StackdriverLogging \\\n --base-image java21 \\\n --region \u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e\n\n Replace:\n - \u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e with the Google Cloud\n [region](/run/docs/locations) where you want to deploy\n your function. For example, `europe-west1`.\n\n - The `--function` flag specifies the entry point to the function in\n example source code. This is the code Cloud Run executes when\n your function runs. The value of this flag must be a function name or\n fully-qualified class name that exists in your source code.\n\n - The `--base-image` flag specifies the base image environment for your\n function. For more details about base images and the packages included\n in each image, see [Runtimes base images](/run/docs/configuring/services/runtime-base-images#how_to_obtain_runtime_base_images).\n\n2. Run the following command to create a trigger that filters events:\n\n gcloud eventarc triggers create \u003cvar translate=\"no\"\u003eTRIGGER_NAME\u003c/var\u003e \\\n --location=\u003cvar translate=\"no\"\u003eEVENTARC_TRIGGER_LOCATION\u003c/var\u003e \\\n --destination-run-service=\u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e \\\n --destination-run-region=\u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e \\\n --event-filters=\"type=google.cloud.pubsub.topic.v1.messagePublished\" \\\n --service-account=\u003cvar translate=\"no\"\u003ePROJECT_NUMBER\u003c/var\u003e-compute@developer.gserviceaccount.com\n\n Replace:\n - \u003cvar translate=\"no\"\u003eTRIGGER_NAME\u003c/var\u003e with the name for your trigger.\n\n - \u003cvar translate=\"no\"\u003eEVENTARC_TRIGGER_LOCATION\u003c/var\u003e with the location for\n the Eventarc trigger. In general, the location of an\n Eventarc trigger should match the location of the Google Cloud resource that you want to monitor for events. In most scenarios, you should also deploy your function in the same region. See [Understand Eventarc locations](/eventarc/docs/understand-locations) for more details about Eventarc trigger locations.\n\n - \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with the name of the function you are\n deploying.\n\n - \u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e with the Cloud Run [region](/run/docs/locations)\n of the function.\n\n - \u003cvar translate=\"no\"\u003ePROJECT_NUMBER\u003c/var\u003e with your Google Cloud project number. Eventarc triggers are linked to service accounts to use\n as an identity when invoking your function. Your Eventarc trigger's service account must have the permission to invoke your function. By\n default, Cloud Run uses the Default compute service account.\n\n - The `--event-filters` flag specifies the event filters that the trigger\n monitors. An event that matches all the `event-filters`, filters\n triggers calls to your function. Each trigger must have a supported\n [event type](/eventarc/docs/reference/supported-events#directly-from-a-google-cloud-source). You can't change\n the event filter type after creation. To change the event filter\n type, you must create a new trigger and delete the old one. Optionally,\n you can repeat the `--event-filters` flag with a supported filter in\n the form `ATTRIBUTE=VALUE` to add more filters.\n\nCloud log entry\n---------------\n\nWhen a Cloud log entry that matches one of your filters is created, the\ncorresponding log entries for your function in the\n[Google Cloud console](https://console.cloud.google.com/logs/viewer?resource=cloud_run_revision) should\nlook as follows: \n\n```bash\nMethod: METHOD\nResource: projects/YOUR_GCLOUD_PROJECT/...\nInitiator: YOUR_EMAIL_ADDRESS\n```"]]