Create an event handler that receives and processes a Cloud Audit Log event with Cloud Storage data
Stay organized with collections
Save and categorize content based on your preferences.
Creates an event handler that receives an incoming Cloud Audit Log event within an HTTP POST request as a CloudEvent.
Explore further
For detailed documentation that includes this code sample, see the following:
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 code demonstrates how to create an event handler that processes incoming Cloud Audit Log events within HTTP POST requests, formatted as CloudEvents.\u003c/p\u003e\n"],["\u003cp\u003eThe examples showcase how to extract the \u003ccode\u003ece-subject\u003c/code\u003e header from a CloudEvent, which contains information about the event's origin, such as the name of a Cloud Storage bucket.\u003c/p\u003e\n"],["\u003cp\u003eThe event handler code is provided in C#, Go, Java, Node.js, and Python, demonstrating language-specific ways of receiving and processing CloudEvents.\u003c/p\u003e\n"],["\u003cp\u003eAuthentication with Eventarc requires setting up Application Default Credentials (ADC), and the documentation provides a link to information on how to do this for local development.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples provide a response to the client with the detected event, indicating if the request is valid or if a required parameter is missing.\u003c/p\u003e\n"]]],[],null,["Creates an event handler that receives an incoming Cloud Audit Log event within an HTTP POST request as a CloudEvent.\n\nExplore further\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Develop event receivers](/eventarc/standard/docs/run/event-receivers)\n- [Tutorial: Debug routing events to Cloud Run](/eventarc/standard/docs/run/debugging-events-cloud-run)\n\nCode sample \n\nC#\n\n\nTo authenticate to Eventarc, 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 using Microsoft.AspNetCore.Builder;\n using Microsoft.AspNetCore.Hosting;\n using Microsoft.AspNetCore.Http;\n using https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Security.PublicCA.V1/latest/Microsoft.Extensions.DependencyInjection.html;\n using Microsoft.Extensions.Hosting;\n using Microsoft.Extensions.Logging;\n\n public class Startup\n {\n public void ConfigureServices(IServiceCollection services)\n {\n }\n\n public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger\u003cStartup\u003e logger)\n {\n if (env.IsDevelopment())\n {\n app.UseDeveloperExceptionPage();\n }\n\n logger.LogInformation(\"Service is starting...\");\n\n app.UseRouting();\n\n app.UseEndpoints(endpoints =\u003e\n {\n endpoints.MapPost(\"/\", async context =\u003e\n {\n logger.LogInformation(\"Handling HTTP POST\");\n\n var ceSubject = context.Request.Headers[\"ce-subject\"];\n logger.LogInformation($\"ce-subject: {ceSubject}\");\n\n if (string.IsNullOrEmpty(ceSubject))\n {\n context.Response.StatusCode = 400;\n await context.Response.WriteAsync(\"Bad Request: expected header Ce-Subject\");\n return;\n }\n\n await context.Response.WriteAsync($\"GCS CloudEvent type: {ceSubject}\");\n });\n });\n }\n }\n\nGo\n\n\nTo authenticate to Eventarc, 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 // Processes CloudEvents containing Cloud Audit Logs for Cloud Storage\n package main\n\n import (\n \t\"fmt\"\n \t\"log\"\n \t\"net/http\"\n \t\"os\"\n\n \tcloudevent \"github.com/cloudevents/sdk-go/v2\"\n )\n\n // HelloEventsStorage receives and processes a Cloud Audit Log event with Cloud Storage data.\n func HelloEventsStorage(w http.ResponseWriter, r *http.Request) {\n \tif r.Method != http.MethodPost {\n \t\thttp.Error(w, \"Expected HTTP POST request with CloudEvent payload\", http.StatusMethodNotAllowed)\n \t\treturn\n \t}\n\n \tevent, err := cloudevent.NewEventFromHTTPRequest(r)\n \tif err != nil {\n \t\tlog.Printf(\"cloudevent.NewEventFromHTTPRequest: %v\", err)\n \t\thttp.Error(w, \"Failed to create CloudEvent from request.\", http.StatusBadRequest)\n \t\treturn\n \t}\n \ts := fmt.Sprintf(\"Detected change in Cloud Storage bucket: %s\", event.Subject())\n \tfmt.Fprintln(w, s)\n }\n\nJava\n\n\nTo authenticate to Eventarc, 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 io.cloudevents.CloudEvent;\n import io.cloudevents.rw.CloudEventRWException;\n import io.cloudevents.spring.http.CloudEventHttpUtils;\n import org.springframework.http.HttpHeaders;\n import org.springframework.http.HttpStatus;\n import org.springframework.http.ResponseEntity;\n import org.springframework.web.bind.annotation.RequestBody;\n import org.springframework.web.bind.annotation.RequestHeader;\n import org.springframework.web.bind.annotation.RequestMapping;\n import org.springframework.web.bind.annotation.RequestMethod;\n import org.springframework.web.bind.annotation.RestController;\n\n @RestController\n public class EventController {\n\n @RequestMapping(value = \"/\", method = RequestMethod.POST, consumes = \"application/json\")\n public ResponseEntity\u003cString\u003e receiveMessage(\n @RequestBody String body, @RequestHeader HttpHeaders headers) {\n CloudEvent event;\n try {\n event =\n CloudEventHttpUtils.fromHttp(headers)\n .withData(headers.getContentType().toString(), body.getBytes())\n .build();\n } catch (CloudEventRWException e) {\n return new ResponseEntity\u003c\u003e(e.getMessage(), HttpStatus.BAD_REQUEST);\n }\n\n String ceSubject = event.getSubject();\n String msg = \"Detected change in Cloud Storage bucket: \" + ceSubject;\n System.out.println(msg);\n return new ResponseEntity\u003c\u003e(msg, HttpStatus.OK);\n }\n }\n\nNode.js\n\n\nTo authenticate to Eventarc, 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 express = require('express');\n const app = express();\n\n app.use(express.json());\n app.post('/', (req, res) =\u003e {\n if (!req.header('ce-subject')) {\n return res\n .status(400)\n .send('Bad Request: missing required header: ce-subject');\n }\n\n console.log(\n `Detected change in Cloud Storage bucket: ${req.header('ce-subject')}`\n );\n return res\n .status(200)\n .send(\n `Detected change in Cloud Storage bucket: ${req.header('ce-subject')}`\n );\n });\n\n module.exports = app;\n\nPython\n\n\nTo authenticate to Eventarc, 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 @app.route(\"/\", methods=[\"POST\"])\n def index():\n # Create a CloudEvent object from the incoming request\n event = from_http(request.headers, request.data)\n # Gets the GCS bucket name from the CloudEvent\n # Example: \"storage.googleapis.com/projects/_/buckets/my-bucket\"\n bucket = event.get(\"subject\")\n\n print(f\"Detected change in Cloud Storage bucket: {bucket}\")\n return (f\"Detected change in Cloud Storage bucket: {bucket}\", 200)\n\nWhat's next\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=eventarc)."]]