Esta página mostra um exemplo de como acionar funções a partir de entradas de registo encaminhadas
para um tópico Pub/Sub.
Estrutura de eventos de funções acionadas pelo Pub/Sub
Tal como todas as funções acionadas pelo Pub/Sub, as funções acionadas por entradas de registo do Cloud Logging recebem um objeto PubsubMessage cujo parâmetro data é uma string codificada em base64. Para eventos de registo do Cloud Logging, a descodificação deste valor devolve a entrada de registo relevante como uma string JSON.
Antes de começar
O código de exemplo encaminha os registos de auditoria do Cloud para uma função do Cloud Run.
Antes de executar o código de exemplo, precisa do seguinte:
// 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}
Para configurar um acionador durante a implementação da função:
Execute o seguinte comando no diretório que contém o código de exemplo
para implementar a sua função:
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
Ir
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
Substituir:
REGION com a Google Cloud
região onde quer implementar
a sua função. Por exemplo, europe-west1.
A flag --function especifica o ponto de entrada para a função no código fonte de exemplo. Este é o código que o Cloud Run executa quando a sua função é executada. O valor desta flag tem de ser um nome de função ou um nome de classe totalmente qualificado que exista no seu código-fonte.
A flag --base-image especifica o ambiente de imagem base para a sua função. Para mais detalhes sobre as imagens base e os pacotes incluídos em cada imagem, consulte o artigo Imagens base de tempos de execução.
Execute o seguinte comando para criar um acionador que filtra eventos:
EVENTARC_TRIGGER_LOCATION com a localização do acionador do Eventarc. Em geral, a localização de um acionador do Eventarc deve corresponder à localização do Google Cloud recurso que quer monitorizar para eventos. Na maioria dos cenários, também deve implementar a função na mesma região. Consulte o artigo Compreender as localizações do Eventarc para ver mais detalhes sobre as localizações dos acionadores do Eventarc.
SERVICE com o nome da função que está a implementar.
PROJECT_NUMBER com o seu Google Cloud número do projeto. Os acionadores do Eventarc estão associados a contas de serviço para serem usados como uma identidade quando invocam a sua função. A conta de serviço do seu acionador do Eventarc tem de ter autorização para invocar a sua função. Por predefinição, o Cloud Run usa a conta de serviço de computação predefinida.
A flag --event-filters especifica os filtros de eventos que o acionador monitoriza. Um evento que corresponde a todos os event-filters, filtros
aciona chamadas para a sua função. Cada acionador tem de ter um tipo de evento suportado. Não pode alterar o tipo de filtro de eventos após a criação. Para alterar o tipo de filtro de eventos, tem de criar um novo acionador e eliminar o antigo. Opcionalmente,
pode repetir a flag --event-filters com um filtro suportado no
formulário ATTRIBUTE=VALUE para adicionar mais filtros.
Entrada do registo na nuvem
Quando é criada uma entrada de registo da nuvem que corresponde a um dos seus filtros, as entradas de registo correspondentes para a sua função na Google Cloud consola devem ter o seguinte aspeto:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-21 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```"]]