Processar os registros de auditoria do Cloud com o Cloud Functions
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Este exemplo demonstra como processar os Registros de auditoria do Cloud usando o Cloud Functions. Ele extrai e imprime o nome do método, o nome do recurso e o e-mail do iniciador de cada entrada de registro.
Exemplo de código
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
[[["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"]],[],[[["\u003cp\u003eThis code provides examples of processing Cloud Audit Logs using Cloud Functions in Go, Java, Node.js, and Python.\u003c/p\u003e\n"],["\u003cp\u003eEach code sample demonstrates extracting data from Pub/Sub messages, which contain log entry data in the form of base64 encoded strings.\u003c/p\u003e\n"],["\u003cp\u003eThe provided functions can retrieve and print key information, including method name, resource name, and initiator email, from log entries.\u003c/p\u003e\n"],["\u003cp\u003eThe samples in each language showcase how to decode log entry information and handle it accordingly, with Java being the exception, which demonstrates handling a JSON-encoded string.\u003c/p\u003e\n"]]],[],null,["# Process Cloud Audit Logs with Cloud Functions\n\nThis sample demonstrates how to process Cloud Audit Logs using Cloud Functions. It extracts and prints the method name, resource name, and initiator email from each log entry.\n\nCode sample\n-----------\n\n### Go\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package log contains examples for handling Cloud Functions logs.\n package log\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"log\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n \t\"github.com/cloudevents/sdk-go/v2/event\"\n )\n\n func init() {\n \tfunctions.CloudEvent(\"ProcessLogEntry\", ProcessLogEntry)\n }\n\n // MessagePublishedData contains the full Pub/Sub message\n // See the documentation for more details:\n // https://cloud.google.com/eventarc/docs/cloudevents#pubsub\n type MessagePublishedData struct {\n \tMessage PubSubMessage\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, e event.Event) error {\n \tvar msg MessagePublishedData\n \tif err := e.DataAs(&msg); err != nil {\n \t\treturn fmt.Errorf(\"event.DataAs: %w\", err)\n \t}\n\n \tlog.Printf(\"Log entry data: %s\", string(msg.Message.Data)) // Automatically decoded from base64.\n \treturn nil\n }\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import com.google.cloud.functions.CloudEventsFunction;\n import com.google.gson.Gson;\n import com.google.gson.JsonElement;\n import com.google.gson.JsonObject;\n import functions.eventpojos.PubSubBody;\n import io.cloudevents.CloudEvent;\n import java.nio.charset.StandardCharsets;\n import java.util.Base64;\n import java.util.logging.Logger;\n\n public class StackdriverLogging implements CloudEventsFunction {\n private static final Logger logger = Logger.getLogger(StackdriverLogging.class.getName());\n // Use Gson (https://github.com/google/gson) to parse JSON content.\n private static final Gson gson = new Gson();\n\n @Override\n public void accept(CloudEvent event) throws Exception {\n if (event.getData() == null) {\n logger.info(\"Hello, World!\");\n return;\n }\n\n // Extract Cloud Event data and convert to PubSubBody\n String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);\n PubSubBody body = gson.fromJson(cloudEventData, PubSubBody.class);\n\n String encodedData = body.getMessage().getData();\n String decodedData = new String(Base64\n .getDecoder().decode(encodedData), StandardCharsets.UTF_8);\n\n // Retrieve and decode PubSubMessage data into a JsonElement.\n // Function is expecting a user-supplied JSON message which contains what\n // name to log.\n JsonElement jsonPubSubMessageElement = gson.fromJson(decodedData, JsonElement.class);\n\n // Extract name if present or default to World\n String name = \"World\";\n if (jsonPubSubMessageElement != null && jsonPubSubMessageElement.isJsonObject()) {\n JsonObject jsonPubSubMessageObject = jsonPubSubMessageElement.getAsJsonObject();\n\n if (jsonPubSubMessageObject.has(\"name\")\n && jsonPubSubMessageObject.get(\"name\").isJsonPrimitive()\n && jsonPubSubMessageObject.get(\"name\").getAsJsonPrimitive().isString()) {\n name = jsonPubSubMessageObject.get(\"name\").getAsString();\n }\n }\n\n String res = String.format(\"Hello, %s!\", name);\n logger.info(res);\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const functions = require('@google-cloud/functions-framework');\n\n functions.cloudEvent('processLogEntry', async event =\u003e {\n const dataBuffer = Buffer.from(event.data.message.data, 'base64');\n\n const logEntry = JSON.parse(dataBuffer.toString()).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\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import base64\n import json\n\n import functions_framework\n\n\n @functions_framework.cloud_event\n def process_log_entry(event):\n data_buffer = base64.b64decode(event.data[\"message\"][\"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\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]