使用 Cloud Functions 处理 Cloud Audit Logs

此示例演示了如何使用 Cloud Functions 处理 Cloud Audit Logs。该示例会从每个日志条目中提取并输出方法名称、资源名称和发起者电子邮件地址。

代码示例

Go

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


// Package log contains examples for handling Cloud Functions logs.
package log

import (
	"context"
	"fmt"
	"log"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
)

func init() {
	functions.CloudEvent("ProcessLogEntry", ProcessLogEntry)
}

// MessagePublishedData contains the full Pub/Sub message
// See the documentation for more details:
// https://cloud.google.com/eventarc/docs/cloudevents#pubsub
type MessagePublishedData struct {
	Message PubSubMessage
}

// PubSubMessage is the payload of a Pub/Sub event.
// See the documentation for more details:
// https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
type PubSubMessage struct {
	Data []byte `json:"data"`
}

// ProcessLogEntry processes a Pub/Sub message from Cloud Logging.
func ProcessLogEntry(ctx context.Context, e event.Event) error {
	var msg MessagePublishedData
	if err := e.DataAs(&msg); err != nil {
		return fmt.Errorf("event.DataAs: %w", err)
	}

	log.Printf("Log entry data: %s", string(msg.Message.Data)) // Automatically decoded from base64.
	return nil
}

Java

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.functions.CloudEventsFunction;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import functions.eventpojos.PubSubBody;
import io.cloudevents.CloudEvent;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Logger;

public class StackdriverLogging implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(StackdriverLogging.class.getName());
  // Use Gson (https://github.com/google/gson) to parse JSON content.
  private static final Gson gson = new Gson();

  @Override
  public void accept(CloudEvent event) throws Exception {
    if (event.getData() == null) {
      logger.info("Hello, World!");
      return;
    }

    // Extract Cloud Event data and convert to PubSubBody
    String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
    PubSubBody body = gson.fromJson(cloudEventData, PubSubBody.class);

    String encodedData = body.getMessage().getData();
    String decodedData = new String(Base64
        .getDecoder().decode(encodedData), StandardCharsets.UTF_8);

    // Retrieve and decode PubSubMessage data into a JsonElement.
    // Function is expecting a user-supplied JSON message which contains what
    // name to log.
    JsonElement jsonPubSubMessageElement = gson.fromJson(decodedData, JsonElement.class);

    // Extract name if present or default to World
    String name = "World";
    if (jsonPubSubMessageElement != null && jsonPubSubMessageElement.isJsonObject()) {
      JsonObject jsonPubSubMessageObject = jsonPubSubMessageElement.getAsJsonObject();

      if (jsonPubSubMessageObject.has("name")
          && jsonPubSubMessageObject.get("name").isJsonPrimitive()
          && jsonPubSubMessageObject.get("name").getAsJsonPrimitive().isString()) {
        name = jsonPubSubMessageObject.get("name").getAsString();
      }
    }

    String res = String.format("Hello, %s!", name);
    logger.info(res);
  }
}

Node.js

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

const functions = require('@google-cloud/functions-framework');

functions.cloudEvent('processLogEntry', async event => {
  const dataBuffer = Buffer.from(event.data.message.data, 'base64');

  const logEntry = JSON.parse(dataBuffer.toString()).protoPayload;
  console.log(`Method: ${logEntry.methodName}`);
  console.log(`Resource: ${logEntry.resourceName}`);
  console.log(`Initiator: ${logEntry.authenticationInfo.principalEmail}`);
});

Python

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import base64
import json

import functions_framework


@functions_framework.cloud_event
def process_log_entry(event):
    data_buffer = base64.b64decode(event.data["message"]["data"])
    log_entry = json.loads(data_buffer)["protoPayload"]

    print(f"Method: {log_entry['methodName']}")
    print(f"Resource: {log_entry['resourceName']}")
    print(f"Initiator: {log_entry['authenticationInfo']['principalEmail']}")

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器