Todos os produtos
Search
Central de documentação

Object Storage Service:Logging via OSS SDK para Go 2.0

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) gera logs de acesso para registrar o acesso aos recursos armazenados em buckets do OSS. Após habilitar o logging para um bucket, o OSS gera logs de acesso a cada hora com base em regras de nomenclatura predefinidas e armazena os logs no bucket especificado.

Notas de uso

  • O código de exemplo neste tópico usa o ID da região cn-hangzhou da região China (Hangzhou). Por padrão, o endpoint público é usado para acessar recursos em um bucket. Se você quiser acessar recursos no bucket a partir de outros serviços da Alibaba Cloud na mesma região em que o bucket está localizado, recomendamos que você use um endpoint interno. Para obter uma lista de regiões e endpoints para o OSS, consulte Regiões e endpoints.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para obter mais informações sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Go SDK V1).

  • Para habilitar o logging para um bucket, você deve ter a permissão oss:PutBucketLogging. Para consultar as configurações de logging de um bucket, você deve ter a permissão oss:GetBucketLogging. Para desabilitar o logging para um bucket, você deve ter a permissão oss:DeleteBucketLogging. Para obter mais informações sobre como conceder permissões, consulte Conceder uma política personalizada.

Código de exemplo

Habilitar logging

O código a seguir habilita o logging para um 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 as configurações de logging de um bucket

O código a seguir consulta as configurações de logging de um 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)
}

Desabilitar logging para um bucket

O código a seguir desabilita o logging para um 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 log personalizados

Você pode chamar a operação PutUserDefinedLogFieldsConfig para configurar o campo user_defined_log_fields, que contém campos de log personalizados. Esses campos de log personalizados podem incluir cabeçalhos de requisição ou parâmetros de consulta pertinentes à sua análise subsequente de requisições. O código de exemplo a seguir configura campos de log personalizados para um 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 configurações de campos de log personalizados

Você pode chamar a operação GetUserDefinedLogFieldsConfig para consultar as configurações user_defined_log_fields. O código de exemplo a seguir consulta as configurações de campos de log personalizados para um 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), // 设置目标 Bucket 名称
	}

	// 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)
}

Excluir configurações de campos de log personalizados

Você pode chamar a operação DeleteUserDefinedLogFieldsConfig para excluir configurações personalizadas user_defined_log_fields. O código de exemplo a seguir exclui configurações de campos de log personalizados para um 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)
}

Referências

  • Para obter mais informações sobre a operação de API que habilita o logging para um bucket, consulte PutBucketLogging.

  • Para obter mais informações sobre a operação de API que consulta as configurações de logging de um bucket, consulte GetBucketLogging.

  • Para obter mais informações sobre a operação de API que desabilita o logging para um bucket, consulte DeleteBucketLogging.

  • Para obter mais informações sobre a operação de API que configura campos de log personalizados, consulte PutUserDefinedLogFieldsConfig.

  • Para obter mais informações sobre a operação de API que consulta configurações de campos de log personalizados, consulte GetUserDefinedLogFieldsConfig.

  • Para obter mais informações sobre a operação de API que exclui configurações de campos de log personalizados, DeleteUserDefinedLogFieldsConfig.