Traiter des journaux d'audit Cloud avec Cloud Functions
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Cet exemple montre comment traiter des journaux d'audit Cloud à l'aide de Cloud Functions. Il extrait et imprime le nom de la méthode, le nom de la ressource et l'adresse e-mail de l'initiateur de chaque entrée de journal.
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","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)."]]