많은 Google Cloud 이벤트가 Cloud 감사 로그에 로깅됩니다. 이러한 로그를 필터링하고 싱크를 사용하여 Pub/Sub 주제로 전달할 수 있습니다. 그런 다음 이러한 Pub/Sub 주제에서 Cloud Run Functions를 트리거하는 알림을 전송할 수 있습니다. 감사 로그를 생성하는 모든 Google Cloud 서비스에서 커스텀 이벤트를 만들 수 있습니다.
이 페이지에서는 Pub/Sub 주제로 라우팅된 로그 항목에서 함수를 트리거하는 방법의 예시를 보여줍니다.
Pub/Sub 트리거 함수의 이벤트 구조
모든 Pub/Sub 트리거 함수와 마찬가지로, Cloud Logging 로그 항목에 의해 트리거된 함수는 PubsubMessage 객체를 수신하며 data 매개변수는 base64로 인코딩된 문자열입니다. Cloud Logging 로그 이벤트의 경우 이 값을 디코딩하면 관련 로그 항목이 JSON 문자열로 반환됩니다.
시작하기 전에
샘플 코드는 Cloud 감사 로그를 Cloud Run 함수에 전달합니다.
샘플 코드를 실행하기 전에 다음이 필요합니다.
// 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}
EVENTARC_TRIGGER_LOCATION을 Eventarc 트리거 위치로 바꿉니다. 일반적으로 Eventarc 트리거 위치는 이벤트를 모니터링하려는 Google Cloud 리소스 위치와 일치해야 합니다. 대부분의 시나리오에서는 함수도 동일한 리전에 배포해야 합니다. Eventarc 트리거 위치에 대한 자세한 내용은 Eventarc 위치 이해를 참조하세요.
PROJECT_NUMBER를 Google Cloud 프로젝트 번호로 바꿉니다. Eventarc 트리거는 함수를 호출할 때 ID로 사용할 서비스 계정에 연결됩니다. Eventarc 트리거 서비스 계정에는 함수를 호출할 수 있는 권한이 있어야 합니다. 기본적으로 Cloud Run은 기본 컴퓨팅 서비스 계정을 사용합니다.
--event-filters 플래그는 트리거에서 모니터링하는 이벤트 필터를 지정합니다. 모든 event-filters 필터와 일치하는 이벤트에서 함수 호출을 트리거합니다. 각 트리거는 지원되는 이벤트 유형이어야 합니다. 생성 후에는 이벤트 필터 유형을 변경할 수 없습니다. 이벤트 필터 유형을 변경하려면 새 트리거를 만들고 이전 트리거를 삭제해야 합니다. 선택적으로 ATTRIBUTE=VALUE 형식으로 지원되는 필터를 사용해서 --event-filters 플래그를 반복하여 더 많은 필터를 추가할 수 있습니다.
Cloud 로그 항목
필터 중 하나와 일치하는 Cloud 로그 항목이 만들어지면 Google Cloud 콘솔의 함수에 대한 해당 로그 항목이 다음과 같이 표시됩니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-15(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```"]]