Trigger functions from log entries Stay organized with collections Save and categorize content based on your preferences.
Many Google Cloud events are logged in Cloud Audit Logs. You canfilter these logs and forward them to Pub/Sub topics usingsinks. These Pub/Sub topics can then send notificationsthattrigger Cloud Run functions. You cancreate custom events from any Google Cloud service that producesaudit logs.
This page shows an example of how to trigger functions from log entries routedto a Pub/Sub topic.
Event structure of Pub/Sub-triggered functions
Like allPub/Sub-triggered functions, functionstriggered by Cloud Logging log entries receive aPubsubMessage object whosedata parameter is abase64-encoded string. For Cloud Logging log events, decoding this valuereturns 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:
See thePub/Sub triggers guide for the APIs to enableand the required roles for deploying functions that are triggered byPub/Sub.
Sample code
You can use aPub/Sub-triggered function to detect andrespond to exported Cloud Logging logs:
Node.js
exports.processLogEntry=data=>{constdataBuffer=Buffer.from(data.data,'base64');constlogEntry=JSON.parse(dataBuffer.toString('ascii')).protoPayload;console.log(`Method:${logEntry.methodName}`);console.log(`Resource:${logEntry.resourceName}`);console.log(`Initiator:${logEntry.authenticationInfo.principalEmail}`);};Python
importbase64importjsondefprocess_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.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}Java
importcom.google.cloud.functions.BackgroundFunction;importcom.google.cloud.functions.Context;importfunctions.eventpojos.PubsubMessage;importjava.nio.charset.StandardCharsets;importjava.util.Base64;importjava.util.logging.Logger;publicclassStackdriverLoggingimplementsBackgroundFunction<PubsubMessage>{privatestaticfinalLoggerlogger=Logger.getLogger(StackdriverLogging.class.getName());@Overridepublicvoidaccept(PubsubMessagemessage,Contextcontext){Stringname="World";if(!message.getData().isEmpty()){name=newString(Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),StandardCharsets.UTF_8);}Stringres=String.format("Hello, %s",name);logger.info(res);}}Deploy and trigger a function
To configure a trigger during function deployment:
Run the following command in the directory that contains the sample codeto deploy your function:
Node.js
gcloud run deploy nodejs-log-function \ --source . \ --function processLogEntry \ --base-image nodejs20 \ --regionREGIONPython
gcloud run deploy python-log-function \ --source . \ --function process_log_entry \ --base-image python312 \ --regionREGIONGo
gcloud run deploy go-log-function \ --source . \ --function ProcessLogEntry \ --base-image go122 \ --regionREGIONJava
gcloud run deploy java-log-function \ --source . \ --function StackdriverLogging \ --base-image java21 \ --regionREGIONReplace:
REGION with the Google Cloudregion where you want to deployyour function. For example,
europe-west1.The
--functionflag specifies the entry point to the function inexample source code. This is the code Cloud Run executes whenyour function runs. The value of this flag must be a function name orfully-qualified class name that exists in your source code.The
--base-imageflag specifies the base image environment for yourfunction. For more details about base images and the packages includedin each image, seeRuntimes base images.
Run the following command to create a trigger that filters events:
gcloud eventarc triggers createTRIGGER_NAME \ --location=EVENTARC_TRIGGER_LOCATION \ --destination-run-service=SERVICE \ --destination-run-region=REGION \ --event-filters="type=google.cloud.pubsub.topic.v1.messagePublished" \ --service-account=PROJECT_NUMBER-compute@developer.gserviceaccount.comReplace:
TRIGGER_NAME with the name for your trigger.
EVENTARC_TRIGGER_LOCATION with the location forthe Eventarc trigger. In general, the location of anEventarc 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. SeeUnderstand Eventarc locations for more details about Eventarc trigger locations.
SERVICE with the name of the function you aredeploying.
REGION with the Cloud Runregionof the function.
PROJECT_NUMBER with your Google Cloud project number. Eventarc triggers are linked to service accounts to useas an identity when invoking your function. Your Eventarc trigger's service account must have the permission to invoke your function. Bydefault, Cloud Run uses the Default compute service account.
The
--event-filtersflag specifies the event filters that the triggermonitors. An event that matches all theevent-filters, filterstriggers calls to your function. Each trigger must have a supportedevent type. You can't changethe event filter type after creation. To change the event filtertype, you must create a new trigger and delete the old one. Optionally,you can repeat the--event-filtersflag with a supported filter inthe formATTRIBUTE=VALUEto add more filters.
Cloud log entry
When a Cloud log entry that matches one of your filters is created, thecorresponding log entries for your function in theGoogle Cloud console shouldlook as follows:
Method:METHODResource:projects/YOUR_GCLOUD_PROJECT/...Initiator:YOUR_EMAIL_ADDRESS
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.