Cloud Functions を使用して Cloud Audit Logs を処理する
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
このサンプルでは、Cloud Functions を使用して Cloud Audit Logs を処理する方法を示します。各ログエントリからメソッド名、リソース名、イニシエータのメールアドレスを抽出して出力します。
コードサンプル
Go
Cloud Run functions に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
Java
Cloud Run functions に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
Node.js
Cloud Run functions に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
Python
Cloud Run functions に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["わかりにくい","hardToUnderstand","thumb-down"],["情報またはサンプルコードが不正確","incorrectInformationOrSampleCode","thumb-down"],["必要な情報 / サンプルがない","missingTheInformationSamplesINeed","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["その他","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)."]]