Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Molti Google Cloud eventi vengono registrati in Cloud Audit Logs. Puoi
filtrarli e inoltrarli agli argomenti Pub/Sub utilizzando i
sink. Questi argomenti Pub/Sub possono quindi inviare notifiche che attivano le funzioni Cloud Run. Puoi
creare eventi personalizzati da qualsiasi servizio Google Cloud che produce
log di controllo.
Questa pagina mostra un esempio di come attivare le funzioni dalle voci di log indirizzate
a un argomento Pub/Sub.
Struttura degli eventi delle funzioni attivate da Pub/Sub
Come tutte le funzioni attivate da Pub/Sub, le funzioni
attivate dalle voci di log di Cloud Logging ricevono un
oggetto PubsubMessage il cui parametro data è una
stringa con codifica base64. Per gli eventi di log di Cloud Logging, la decodifica di questo valore
restituisce la voce di log pertinente come stringa JSON.
Prima di iniziare
Il codice campione inoltra Cloud Audit Logs a una funzione Cloud Run.
Prima di eseguire il codice campione, ti serviranno:
// 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}
Per configurare un trigger durante il deployment della funzione:
Esegui questo comando nella directory che contiene il codice campione
per eseguire il deployment della funzione:
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
Vai
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
Sostituisci:
REGION con la Google Cloud
regione in cui vuoi eseguire il deployment
della funzione. Ad esempio: europe-west1.
Il flag --function specifica l'entry point della funzione nel
codice sorgente di esempio. Questo è il codice che Cloud Run esegue quando
la funzione viene eseguita. Il valore di questo flag deve essere un nome di funzione o
un nome di classe completo che esiste nel codice sorgente.
Il flag --base-image specifica l'ambiente dell'immagine di base per la tua funzione. Per maggiori dettagli sulle immagini di base e sui pacchetti inclusi
in ogni immagine, consulta Immagini di base dei runtime.
Esegui questo comando per creare un trigger che filtri gli eventi:
EVENTARC_TRIGGER_LOCATION con la località del trigger Eventarc. In generale, la località di un
trigger Eventarc deve corrispondere a quella della risorsa Google Cloud che vuoi monitorare per gli eventi. Nella maggior parte degli scenari, devi anche eseguire il deployment della funzione nella stessa regione. Per ulteriori dettagli sulle località dei trigger Eventarc, consulta la sezione Informazioni sulle località Eventarc.
SERVICE con il nome della funzione che stai
eseguendo il deployment.
REGION con la regione di Cloud Run
della funzione.
PROJECT_NUMBER con il numero del tuo progetto Google Cloud . I trigger Eventarc sono collegati agli account di servizio da utilizzare
come identità quando viene richiamata la funzione. Il account di servizio del trigger Eventarc deve disporre dell'autorizzazione per richiamare la funzione. Per impostazione predefinita, Cloud Run utilizza l'account di servizio Compute predefinito.
Il flag --event-filters specifica i filtri eventi monitorati dal trigger. Un evento che corrisponde a tutti i event-filters, i filtri
attiva le chiamate alla tua funzione. Ogni attivatore deve avere un tipo di evento supportato. Non puoi modificare
il tipo di filtro eventi dopo la creazione. Per modificare il tipo di filtro
eventi, devi creare un nuovo trigger ed eliminare quello precedente. (Facoltativo) Puoi ripetere il flag --event-filters con un filtro supportato nel formato ATTRIBUTE=VALUE per aggiungere altri filtri.
Voce di log di Cloud
Quando viene creata una voce di log Cloud che corrisponde a uno dei tuoi filtri, le voci di log corrispondenti per la tua funzione nella console Google Cloud dovrebbero avere il seguente aspetto:
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-04 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```"]]