Stay organized with collections
Save and categorize content based on your preferences.
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. You can
create custom events from any Google Cloud service that produces
audit logs.
This page shows an example of how to trigger functions from log entries routed
to a Pub/Sub topic.
Event structure of Pub/Sub-triggered functions
Like all Pub/Sub-triggered functions, functions
triggered by Cloud Logging log entries receive a
PubsubMessage object whose data parameter is a
base64-encoded string. For Cloud Logging log events, decoding this value
returns the relevant log entry as a JSON string.
Before you begin
The sample code forwards Cloud Audit Logs to a Cloud Run function.
Before you run the sample code, you'll need the following:
// 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}
To configure a trigger during function deployment:
Run the following command in the directory that contains the sample code
to deploy your function:
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
Replace:
REGION with the Google Cloud
region where you want to deploy
your function. For example, europe-west1.
The --function flag specifies the entry point to the function in
example source code. This is the code Cloud Run executes when
your function runs. The value of this flag must be a function name or
fully-qualified class name that exists in your source code.
The --base-image flag specifies the base image environment for your
function. For more details about base images and the packages included
in each image, see Runtimes base images.
Run the following command to create a trigger that filters events:
EVENTARC_TRIGGER_LOCATION with the location for
the Eventarc trigger. In general, the location of an
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 for more details about Eventarc trigger locations.
SERVICE with the name of the function you are
deploying.
PROJECT_NUMBER with your Google Cloud project number. Eventarc triggers are linked to service accounts to use
as an identity when invoking your function. Your Eventarc trigger's service account must have the permission to invoke your function. By
default, Cloud Run uses the Default compute service account.
The --event-filters flag specifies the event filters that the trigger
monitors. An event that matches all the event-filters, filters
triggers calls to your function. Each trigger must have a supported
event type. You can't change
the event filter type after creation. To change the event filter
type, you must create a new trigger and delete the old one. Optionally,
you can repeat the --event-filters flag with a supported filter in
the form ATTRIBUTE=VALUE to add more filters.
Cloud log entry
When a Cloud log entry that matches one of your filters is created, the
corresponding log entries for your function in the
Google Cloud console should
look as follows:
[[["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-08-25 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```"]]