새 함수를 만드는 경우 Cloud Run의
콘솔 빠른 시작을 참고하세요.
Cloud Functions로 Cloud 감사 로그 처리
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
이 샘플은 Cloud Functions를 사용해서 Cloud 감사 로그를 처리하는 방법을 보여줍니다. 각 로그 항목에서 메서드 이름, 리소스 이름, 개시자 이메일을 추출하고 출력합니다.
코드 샘플
Go
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Java
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Node.js
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
Python
Cloud Run Functions에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다.
자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 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)."]]