Process a Cloud Audit Logging log entry
Stay organized with collections
Save and categorize content based on your preferences.
Shows how to process an Audit Log entry.
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page demonstrates how to process a Cloud Audit Log entry using Cloud Functions.\u003c/p\u003e\n"],["\u003cp\u003eThe examples extract and log key fields from the CloudEvent, including event type, subject, API method, resource name, and principal.\u003c/p\u003e\n"],["\u003cp\u003eIt provides code samples in Go, Java, Node.js, and Python, showcasing how to decode the Cloud Audit Logging message embedded in the CloudEvent.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code demonstrates how to access and interpret the \u003ccode\u003eprotoPayload\u003c/code\u003e, a field that contains Cloud Audit Logging information.\u003c/p\u003e\n"],["\u003cp\u003eTo use the code, make sure you set up Application Default Credentials for authentication to Cloud Run functions.\u003c/p\u003e\n"]]],[],null,["# Process a Cloud Audit Logging log entry\n\nShows how to process an Audit 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 helloworld provides a set of Cloud Functions samples.\n package helloworld\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(\"HelloAuditLog\", helloAuditLog)\n }\n\n // AuditLogEntry represents a LogEntry as described at\n // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry\n type AuditLogEntry struct {\n \tProtoPayload *AuditLogProtoPayload `json:\"protoPayload\"`\n }\n\n // AuditLogProtoPayload represents AuditLog within the LogEntry.protoPayload\n // See https://cloud.google.com/logging/docs/reference/audit/auditlog/rest/Shared.Types/AuditLog\n type AuditLogProtoPayload struct {\n \tMethodName string `json:\"methodName\"`\n \tResourceName string `json:\"resourceName\"`\n \tAuthenticationInfo map[string]interface{} `json:\"authenticationInfo\"`\n }\n\n // helloAuditLog receives a CloudEvent containing an AuditLogEntry, and logs a few fields.\n func helloAuditLog(ctx context.Context, e event.Event) error {\n \t// Print out details from the CloudEvent itself\n \t// See https://github.com/cloudevents/spec/blob/v1.0.1/spec.md#subject\n \t// for details on the Subject field\n \tlog.Printf(\"Event Type: %s\", e.Type())\n \tlog.Printf(\"Subject: %s\", e.Subject())\n\n \t// Decode the Cloud Audit Logging message embedded in the CloudEvent\n \tlogentry := &AuditLogEntry{}\n \tif err := e.DataAs(logentry); err != nil {\n \t\tferr := fmt.Errorf(\"event.DataAs: %w\", err)\n \t\tlog.Print(ferr)\n \t\treturn ferr\n \t}\n \t// Print out some of the information contained in the Cloud Audit Logging event\n \t// See https://cloud.google.com/logging/docs/audit#audit_log_entry_structure\n \t// for a full description of available fields.\n \tlog.Printf(\"API Method: %s\", logentry.ProtoPayload.MethodName)\n \tlog.Printf(\"Resource Name: %s\", logentry.ProtoPayload.ResourceName)\n \tif v, ok := logentry.ProtoPayload.AuthenticationInfo[\"principalEmail\"]; ok {\n \t\tlog.Printf(\"Principal: %s\", v)\n \t}\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 import com.google.cloud.functions.CloudEventsFunction;\n import com.google.gson.Gson;\n import com.google.gson.JsonObject;\n import io.cloudevents.CloudEvent;\n import java.nio.charset.StandardCharsets;\n import java.util.logging.Logger;\n\n public class LogCloudEvent implements CloudEventsFunction {\n private static final Logger logger = Logger.getLogger(LogCloudEvent.class.getName());\n\n @Override\n public void accept(CloudEvent event) {\n // Print out details from the CloudEvent\n // The type of event related to the originating occurrence\n logger.info(\"Event Type: \" + event.getType());\n // The subject of the event in the context of the event producer\n logger.info(\"Event Subject: \" + event.getSubject());\n\n if (event.getData() != null) {\n // Extract data from CloudEvent wrapper\n String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);\n\n Gson gson = new Gson();\n // Convert data into a JSON object\n JsonObject eventData = gson.fromJson(cloudEventData, JsonObject.class);\n\n // Extract Cloud Audit Log data from protoPayload\n // https://cloud.google.com/logging/docs/audit#audit_log_entry_structure\n JsonObject payload = eventData.getAsJsonObject(\"protoPayload\");\n logger.info(\"API Method: \" + payload.get(\"methodName\").getAsString());\n logger.info(\"Resource name: \" + payload.get(\"resourceName\").getAsString());\n\n JsonObject auth = payload.getAsJsonObject(\"authenticationInfo\");\n if (auth != null) {\n // The email address of the authenticated user \n // (or service account on behalf of third party principal) making the request\n logger.info(\"Authenticated User: \" + auth.get(\"principalEmail\").getAsString()); \n }\n }\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 // Register a CloudEvent callback with the Functions Framework that will\n // be triggered by an Eventarc Cloud Audit Logging trigger.\n //\n // Note: this is NOT designed for second-party (Cloud Audit Logs -\u003e Pub/Sub) triggers!\n functions.cloudEvent('helloAuditLog', cloudEvent =\u003e {\n // Print out details from the CloudEvent itself\n console.log('Event type:', cloudEvent.type);\n\n // Print out the CloudEvent's `subject` property\n // See https://github.com/cloudevents/spec/blob/v1.0.1/spec.md#subject\n console.log('Subject:', cloudEvent.subject);\n\n // Print out details from the `protoPayload`\n // This field encapsulates a Cloud Audit Logging entry\n // See https://cloud.google.com/logging/docs/audit#audit_log_entry_structure\n const payload = cloudEvent.data && cloudEvent.data.protoPayload;\n if (payload) {\n console.log('API method:', payload.methodName);\n console.log('Resource name:', payload.resourceName);\n console.log('Principal:', payload.authenticationInfo.principalEmail);\n }\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 functions_framework\n\n\n # CloudEvent function to be triggered by an Eventarc Cloud Audit Logging trigger\n # Note: this is NOT designed for second-party (Cloud Audit Logs -\u003e Pub/Sub) triggers!\n @functions_framework.cloud_event\n def hello_auditlog(cloud_event):\n # Print out the CloudEvent's (required) `type` property\n # See https://github.com/cloudevents/spec/blob/v1.0.1/spec.md#type\n print(f\"Event type: {cloud_event['type']}\")\n\n # Print out the CloudEvent's (optional) `subject` property\n # See https://github.com/cloudevents/spec/blob/v1.0.1/spec.md#subject\n if \"subject\" in cloud_event:\n # CloudEvent objects don't support `get` operations.\n # Use the `in` operator to verify `subject` is present.\n print(f\"Subject: {cloud_event['subject']}\")\n\n # Print out details from the `protoPayload`\n # This field encapsulates a Cloud Audit Logging entry\n # See https://cloud.google.com/logging/docs/audit#audit_log_entry_structure\n\n payload = cloud_event.data.get(\"protoPayload\")\n if payload:\n print(f\"API method: {payload.get('methodName')}\")\n print(f\"Resource name: {payload.get('resourceName')}\")\n print(\n f\"Principal: {payload.get('authenticationInfo', dict()).get('principalEmail')}\"\n )\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)."]]