Jika Anda membuat fungsi baru, lihat Panduan Memulai Konsol di Cloud Run. Konten di halaman ini hanya berlaku untuk fungsi lama yang sudah ada yang dibuat dengan Cloud Functions v1 API.
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Pemicu Pihak Kedua dengan Cloud Logging
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. Dengan begitu, Anda dapat membuat peristiwa kustom dari layanan Google Cloud mana pun yang menghasilkan
log audit.
Konfigurasi
Untuk menjalankan contoh dalam dokumen ini, Anda memerlukan
topik Pub/Sub
dan sink Cloud Logging.
Contoh menggunakannya untuk meneruskan Cloud Audit Logs ke fungsi Cloud Run.
Struktur peristiwa
Seperti semua fungsi yang dipicu Pub/Sub, fungsi yang dipicu oleh entri log Cloud menerima objek PubsubMessage yang parameter data-nya adalah String berenkode base64. Untuk peristiwa log Cloud, mendekode nilai ini akan menampilkan entri log yang relevan sebagai string JSON.
Kode contoh
Anda dapat menggunakan fungsi yang dipicu Pub/Sub untuk mendeteksi dan merespons log Cloud yang diekspor:
// 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}
[[["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-08-19 UTC."],[[["\u003cp\u003eCloud Audit Logs can be filtered and forwarded to Pub/Sub topics using sinks, allowing you to create custom events from various Google Cloud services.\u003c/p\u003e\n"],["\u003cp\u003eCloud Run functions can be triggered by notifications from Pub/Sub topics, which receive forwarded Cloud Audit Logs.\u003c/p\u003e\n"],["\u003cp\u003eFunctions triggered by Cloud log entries receive a \u003ccode\u003ePubsubMessage\u003c/code\u003e object, where the \u003ccode\u003edata\u003c/code\u003e parameter, when decoded, provides the log entry as a JSON string.\u003c/p\u003e\n"],["\u003cp\u003eSample code is provided for Node.js, Python, Go, and Java to demonstrate how to process and respond to exported Cloud logs within a Pub/Sub-triggered function.\u003c/p\u003e\n"],["\u003cp\u003eTo deploy a function, you can use the \u003ccode\u003egcloud functions deploy\u003c/code\u003e command and the \u003ccode\u003e--runtime\u003c/code\u003e flag to specify the required runtime.\u003c/p\u003e\n"]]],[],null,["# Second-Party Triggers with Cloud Logging\n========================================\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](/functions/1stgendocs/calling/pubsub) Cloud Run functions. This lets you create custom\nevents from any Google Cloud service that produces\n[audit logs](/logging/docs/audit/services).\n\nConfiguration\n-------------\n\nTo run the sample in this document, you'll need a\n[Pub/Sub topic](/pubsub/docs/create-topic-console#create_a_topic)\nand a [Cloud Logging sink](/logging/docs/export/configure_export_v2#dest-create).\nThe sample uses them to forward Cloud Audit Logs to a Cloud Run function.\n\nEvent structure\n---------------\n\nLike all [Pub/Sub-triggered functions](/functions/1stgendocs/calling/pubsub), functions triggered by\nCloud log entries receive a [`PubsubMessage`](/pubsub/docs/reference/rest/v1/PubsubMessage)\nobject whose `data` parameter is a `base64`-encoded string. For Cloud log\nevents, decoding this value returns the relevant log entry as a JSON string.\n\nSample code\n-----------\n\nYou can use a [Pub/Sub-triggered function](/functions/1stgendocs/calling/pubsub) to detect and\nrespond to exported Cloud 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\nDeploying a function\n--------------------\n\nUse the following command to deploy the function: \n\n### Node.js\n\n```sh\ngcloud functions deploy processLogEntry \\\n--runtime nodejs20 \\\n--trigger-topic YOUR_PUBSUB_TOPIC/\nFLAGS...\n```\n\n\nUse the [`--runtime`](/sdk/gcloud/reference/functions/deploy#--runtime)\nflag to specify the runtime ID of a\n[supported Node.js version](/static/functions/docs/runtime-support#node.js) to run\nyour function.\n\n\n### Python\n\n```sh\ngcloud functions deploy process_log_entry \\\n--runtime python312 \\\n--trigger-topic YOUR_PUBSUB_TOPIC/\nFLAGS...\n```\n\n\nUse the [`--runtime`](/sdk/gcloud/reference/functions/deploy#--runtime)\nflag to specify the runtime ID of a\n[supported Python version](/functions/docs/runtime-support#python) to run\nyour function.\n\n\n### Go\n\n```sh\ngcloud functions deploy ProcessLogEntry \\\n--runtime go121 \\\n--trigger-topic YOUR_PUBSUB_TOPIC/\nFLAGS...\n```\n\n\nUse the [`--runtime`](/sdk/gcloud/reference/functions/deploy#--runtime)\nflag to specify the runtime ID of a\n[supported Go version](/functions/docs/runtime-support#go) to run\nyour function.\n\n\n### Java\n\n```sh\ngcloud functions deploy java-log-function \\\n--entry-point StackdriverLogging \\\n--runtime java17 \\\n--memory 512MB \\\n--trigger-topic YOUR_PUBSUB_TOPIC/\nFLAGS...\n```\n\n\nUse the [`--runtime`](/sdk/gcloud/reference/functions/deploy#--runtime)\nflag to specify the runtime ID of a\n[supported Java version](/functions/docs/runtime-support#java) to run\nyour function.\n\n\nTriggering a function\n---------------------\n\nWhen a Cloud log entry that matches one of your filters is created, you\n[should see](https://console.cloud.google.com/logs/viewer?resource=cloud_function) corresponding\nlog entries for your function: \n\n```bash\nMethod: METHOD\nResource: projects/YOUR_GCLOUD_PROJECT/...\nInitiator: YOUR_EMAIL_ADDRESS\n```"]]