写入请求日志

介绍如何记录 HTTP 请求日志的示例。

代码示例

Go

如需了解如何安装和使用 Logging 客户端库,请参阅 Logging 客户端库

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


// Writes an advanced log entry to Cloud Logging.
package main

import (
	"context"
	"log"
	"net/http"
	"os"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()

	// Creates a client.
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	client, err := logging.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer client.Close()

	// Sets the name of the log to write to.
	logger := client.Logger("my-log")

	// Logs a basic entry.
	logger.Log(logging.Entry{Payload: "hello world"})

	// TODO(developer): replace with your request value.
	r, err := http.NewRequest("GET", "http://example.com", nil)

	// Logs an HTTPRequest type entry.
	// Some request metadata will be autopopulated in the log entry.
	httpEntry := logging.Entry{
		Payload: "optional message",
		HTTPRequest: &logging.HTTPRequest{
			Request: r,
		},
	}
	logger.Log(httpEntry)
}

Java

如需了解如何安装和使用 Logging 客户端库,请参阅 Logging 客户端库

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

import com.google.cloud.MonitoredResource;
import com.google.cloud.logging.HttpRequest;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;
import com.google.cloud.logging.Payload;
import com.google.cloud.logging.Severity;
import java.util.Collections;

/** Write LogEntry with HTTP request using the Cloud Logging API. */
public class LogEntryWriteHttpRequest {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String logName = "log-name"; // i.e "my-log"
    String payLoad = "payload"; // i.e "Hello world!"
    HttpRequest httpRequest =
        HttpRequest.newBuilder()
            .setRequestUrl("www.example.com")
            .setRequestMethod(HttpRequest.RequestMethod.GET) // Supported method GET,POST,PUT,HEAD
            .setStatus(200)
            .build();
    createLogEntryRequest(logName, payLoad, httpRequest);
  }

  public static void createLogEntryRequest(String logName, String payLoad, HttpRequest httpRequest)
      throws Exception {
    // Instantiates a logging client
    try (Logging logging = LoggingOptions.getDefaultInstance().getService()) {
      // create an instance of LogEntry with HTTP request
      LogEntry logEntry =
          LogEntry.newBuilder(Payload.StringPayload.of(payLoad))
              .setSeverity(Severity.ERROR)
              .setLogName(logName)
              .setHttpRequest(httpRequest)
              .setResource(MonitoredResource.newBuilder("global").build())
              .build();

      // Writes the log entry asynchronously
      logging.write(Collections.singleton(logEntry));
      System.out.printf("Logged: %s", payLoad);
    }
  }
}

Node.js

如需了解如何安装和使用 Logging 客户端库,请参阅 Logging 客户端库

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

/*
const projectId = 'YOUR_PROJECT_ID'; // Your Google Cloud Platform project ID
const logName = 'my-log'; // The name of the log to write to
const requestMethod = 'GET'; // GET, POST, PUT, etc.
const requestUrl = 'http://www.google.com';
const status = 200;
const userAgent = `my-user-agent/1.0.0`;
const latencySeconds = 3;
const responseSize = 256; // response size in bytes.
*/

// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');

// Creates a client
const logging = new Logging({projectId});

// Selects the log to write to
const log = logging.log(logName);

// The data to write to the log
const text = 'Hello, world!';

// The metadata associated with the entry
const metadata = {
  resource: {type: 'global'},
  httpRequest: {
    requestMethod,
    requestUrl,
    status,
    userAgent,
    latency: {
      seconds: latencySeconds,
    },
    responseSize,
  },
};

// Prepares a log entry
const entry = log.entry(metadata, text);

// Writes the log entry
async function writeLog() {
  await log.write(entry);
  console.log(`Logged: ${text}`);
}
writeLog();

后续步骤

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