Todos os produtos
Search
Central de documentação

Object Storage Service:Registros de log por meio do OSS SDK for Go 2.0

Última atualização: Oct 10, 2026

O Object Storage Service (OSS) gera logs de acesso para registrar o acesso aos recursos armazenados nos buckets do OSS. Após ativar os logs de 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 de região cn-hangzhou da região China (Hangzhou). Por padrão, o endpoint público é usado para acessar recursos em um bucket. Para acessar recursos no bucket a partir de outros serviços da Alibaba Cloud na mesma região do bucket, recomendamos o uso de um endpoint interno. Para obter a lista de regiões e endpoints do 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 ativar os logs de um bucket, é necessário ter a permissão oss:PutBucketLogging. Para consultar as configurações de log de um bucket, é necessário ter a permissão oss:GetBucketLogging. Para desativar os logs de um bucket, é necessário 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

Ativar logs

O código a seguir ativa os logs 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 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 log de um bucket

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

Desativar os logs de um bucket

O código a seguir desativa os logs 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 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

Chame a operação PutUserDefinedLogFieldsConfig para configurar o campo user_defined_log_fields, que contém campos de log personalizados. Esses campos podem incluir cabeçalhos de solicitação ou parâmetros de consulta relevantes para análises posteriores. 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

Chame a operação GetUserDefinedLogFieldsConfig para consultar as configurações de 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), // 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)
}

Excluir configurações de campos de log personalizados

Chame a operação DeleteUserDefinedLogFieldsConfig para excluir as configurações personalizadas de user_defined_log_fields. O código de exemplo a seguir exclui 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 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 ativa os logs de um bucket, consulte PutBucketLogging.

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

  • Para obter mais informações sobre a operação de API que desativa os logs de 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 as configurações de campos de log personalizados, consulte GetUserDefinedLogFieldsConfig.

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