If you are creating a new function, see the Console Quickstart on Cloud Run. The content on this page only applies to existing legacy functions created with the Cloud Functions v1 API.
Stay organized with collections
Save and categorize content based on your preferences.
Second-Party Triggers with Cloud Logging
Many Google Cloud events are logged in Cloud Audit Logs. You can
filter these logs and forward them to Pub/Sub topics using
sinks. These Pub/Sub topics can then send notifications
that trigger Cloud Run functions. This lets you create custom
events from any Google Cloud service that produces
audit logs.
Configuration
To run the sample in this document, you'll need a
Pub/Sub topic
and a Cloud Logging sink.
The sample uses them to forward Cloud Audit Logs to a Cloud Run function.
Event structure
Like all Pub/Sub-triggered functions, functions triggered by
Cloud log entries receive a PubsubMessage
object whose data parameter is a base64-encoded string. For Cloud log
events, decoding this value returns the relevant log entry as a JSON string.
// 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}
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-03 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```"]]