Todos los productos
Search
Centro de documentos

Object Storage Service:Registro mediante OSS SDK for Go 2.0

Última actualización: Oct 10, 2026

Object Storage Service (OSS) genera registros de acceso para documentar las solicitudes a los recursos almacenados en los buckets de OSS. Cuando usted habilita el registro de un bucket, OSS genera registros de acceso cada hora con base en reglas de nomenclatura predefinidas y los almacena en el bucket especificado.

Notas de uso

  • El código de ejemplo de este tema utiliza el identificador de región cn-hangzhou, correspondiente a China (Hangzhou). De forma predeterminada, se usa el endpoint público para acceder a los recursos de un bucket. Si necesita acceder a los recursos del bucket desde otros servicios de Alibaba Cloud ubicados en la misma región, le recomendamos usar un endpoint interno. Para consultar la lista de regiones y endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen a partir de variables de entorno. Para más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials (Go SDK V1).

  • Para habilitar el registro de un bucket, es obligatorio contar con el permiso oss:PutBucketLogging. Para consultar la configuración de registro de un bucket, es obligatorio contar con el permiso oss:GetBucketLogging. Para deshabilitar el registro de un bucket, es obligatorio contar con el permiso oss:DeleteBucketLogging. Para más información sobre cómo otorgar permisos, consulte Grant a custom policy.

Código de ejemplo

Habilitar el registro

A continuación se muestra el código que habilita el registro de un bucket:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Initialize command-line arguments.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command-line arguments.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configuration and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to enable logging for the bucket.
	putRequest := &oss.PutBucketLoggingRequest{
		Bucket: oss.Ptr(bucketName), // Specify the name of the bucket for which you want to enable logging.
		BucketLoggingStatus: &oss.BucketLoggingStatus{
			LoggingEnabled: &oss.LoggingEnabled{
				TargetBucket: oss.Ptr("TargetBucket"), // Specify the name of the destination bucket in which the log objects are stored. The source and destination buckets can be the same bucket or different buckets in the same region.
				TargetPrefix: oss.Ptr("log"),          // Specify the directory in which the log objects are stored. If you specify this parameter, the logs are stored in the specified directory of the destination bucket. If you do not specify this parameter, the logs are stored in the root directory of the destination bucket.
			},
		},
	}

	// Execute the request.
	putResult, err := client.PutBucketLogging(context.TODO(), putRequest)
	if err != nil {
		log.Fatalf("failed to put bucket logging %v", err)
	}

	// Display the result.
	log.Printf("put bucket logging result:%#v\n", putResult)
}

Consultar la configuración de registro de un bucket

A continuación se muestra el código que consulta la configuración de registro de un bucket:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Initialize command-line arguments.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command-line arguments.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configuration and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to query the logging settings of the bucket.
	getRequest := &oss.GetBucketLoggingRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
	}

	// Perform the query operation and process the result.
	getResult, err := client.GetBucketLogging(context.TODO(), getRequest)
	if err != nil {
		log.Fatalf("failed to get bucket logging %v", err)
	}

	// Display the result.
	log.Printf("get bucket logging result target bucket:%#v\n", getResult.BucketLoggingStatus.LoggingEnabled.TargetBucket)
}

Deshabilitar el registro de un bucket

A continuación se muestra el código que deshabilita el registro de un bucket:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Initialize command-line arguments.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command-line arguments.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified 
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configuration and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to disable logging for the bucket.
	delRequest := &oss.DeleteBucketLoggingRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
	}

	// Execute the request to disable logging and process the result.
	delResult, err := client.DeleteBucketLogging(context.TODO(), delRequest)
	if err != nil {
		log.Fatalf("failed to delete bucket logging %v", err)
	}

	// Display the result.
	log.Printf("delete bucket logging result:%#v\n", delResult)
}

Configurar campos de registro personalizados

Llame a la operación PutUserDefinedLogFieldsConfig para configurar el campo user_defined_log_fields, que contiene campos de registro personalizados. Estos campos pueden incluir encabezados de solicitud o parámetros de consulta relevantes para el análisis posterior de sus solicitudes. El siguiente código de ejemplo configura campos de registro personalizados para un bucket:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Declare variables for storing command-line arguments.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Initialize command-line arguments.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command-line arguments.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configuration and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Construct a PutUserDefinedLogFieldsConfigRequest.
	request := &oss.PutUserDefinedLogFieldsConfigRequest{
		Bucket: oss.Ptr(bucketName), // Specify the bucket name.
		UserDefinedLogFieldsConfiguration: &oss.UserDefinedLogFieldsConfiguration{
			HeaderSet: &oss.LoggingHeaderSet{
				Headers: []string{"header1", "header2"}, // Specify HTTP headers to be logged.
			},
			ParamSet: &oss.LoggingParamSet{
				Parameters: []string{"param"}, // Specify query parameters to be logged.
			},
		},
	}

	// Execute the request.
	result, err := client.PutUserDefinedLogFieldsConfig(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put user defined log fields config %v", err)
	}

	// Display the result.
	log.Printf("put user defined log fields config result:%#v\n", result)
}

Consultar la configuración de campos de registro personalizados

Llame a la operación GetUserDefinedLogFieldsConfig para consultar la configuración de user_defined_log_fields. El siguiente código de ejemplo consulta la configuración de campos de registro personalizados de un bucket:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Declare variables for storing command-line arguments.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Initialize command-line arguments.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command-line arguments.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configuration and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Construct a GetUserDefinedLogFieldsConfigRequest.
	getRequest := &oss.GetUserDefinedLogFieldsConfigRequest{
		Bucket: oss.Ptr(bucketName), // Set the target bucket name
	}

	// Execute the request.
	getResult, err := client.GetUserDefinedLogFieldsConfig(context.TODO(), getRequest)
	if err != nil {
		// In case of an error, display it and exit the program.
		log.Fatalf("failed to get user defined log fields config %v", err)
	}

	// Display the result.
	log.Printf("get user defined log fields config result:%#v\n", getResult)
}

Eliminar la configuración de campos de registro personalizados

Llame a la operación DeleteUserDefinedLogFieldsConfig para eliminar la configuración personalizada de user_defined_log_fields. El siguiente código de ejemplo elimina la configuración de campos de registro personalizados de un bucket:

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Declare variables for storing command-line arguments.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Initialize command-line arguments.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command-line arguments.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configuration and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Construct a DeleteUserDefinedLogFieldsConfigRequest.
	request := &oss.DeleteUserDefinedLogFieldsConfigRequest{
		Bucket: oss.Ptr(bucketName), // Specify the name of the bucket.
	}

	// Execute the request.
	result, err := client.DeleteUserDefinedLogFieldsConfig(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete user defined log fields config %v", err)
	}

	// Display the result.
	log.Printf("delete user defined log fields config result:%#v\n", result)
}

Referencias

  • Para más información sobre la operación de API que habilita el registro de un bucket, consulte PutBucketLogging.

  • Para más información sobre la operación de API que consulta la configuración de registro de un bucket, consulte GetBucketLogging.

  • Para más información sobre la operación de API que deshabilita el registro de un bucket, consulte DeleteBucketLogging.

  • Para más información sobre la operación de API que configura campos de registro personalizados, consulte PutUserDefinedLogFieldsConfig.

  • Para más información sobre la operación de API que consulta la configuración de campos de registro personalizados, consulte GetUserDefinedLogFieldsConfig.

  • Para más información sobre la operación de API que elimina la configuración de campos de registro personalizados, consulte DeleteUserDefinedLogFieldsConfig.