Todos os produtos
Search
Central de documentação

Object Storage Service:Logging (OSS SDK for Go 1.0)

Última atualização: Sep 22, 2026

O registro de logs de acesso do Object Storage Service (OSS) captura informações detalhadas sobre as solicitações feitas aos seus buckets. Depois que o logging é ativado para um bucket de origem, o OSS gera e entrega automaticamente arquivos de log a cada hora para um bucket de destino. Especifique o bucket de destino e utilize uma convenção de nomenclatura predefinida.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Se você precisar acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Configure as credenciais de acesso obtendo-as de variáveis de ambiente. Execute o código de exemplo apenas após garantir que as variáveis estejam configuradas. Para saber mais sobre como configurar as credenciais de acesso, consulte Configure access credentials.

  • Crie uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • O gerenciamento do logging de um bucket exige permissões específicas. Ative a permissão oss:PutBucketLogging para habilitar, visualize com oss:GetBucketLogging para consultar e exclua com oss:DeleteBucketLogging para desativar. Para obter mais informações, consulte Grant a custom policy.

Ativar o logging para um bucket

Defina o bucket de origem e ative o logging com o código de exemplo a seguir:

package main

import (
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create an OSSClient instance. 
        // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Specify the name of the source bucket for which you want to enable logging. Example: examplebucket. 
	bucketName := "examplebucket"
	// Specify the name of the destination bucket in which you want to store the log objects. The source and destination buckets can be the same bucket or different buckets, but they must be located in the same region. 
	targetBucketName := "destbucket"
	// Set the directory in which you want to store the log objects to log/. If you specify this parameter, the log objects are stored in the specified directory of the destination bucket. If you do not specify this parameter, the log objects are stored in the root directory of the destination bucket. 
	targetPrefix := "log/"

	// Enable logging for the bucket. 
	err = client.SetBucketLogging(bucketName, targetBucketName, targetPrefix, true)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}

Consultar as configurações de logging de um bucket

Visualize as configurações de logging de um bucket com o código de exemplo a seguir:

package main

import (
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create an OSSClient instance. 
        // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"

	// View the logging configurations of the bucket. 
	logRes, err := client.GetBucketLogging(bucketName)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Println("Target Bucket: ", logRes.LoggingEnabled.TargetBucket)
	fmt.Println("Target Prefix: ", logRes.LoggingEnabled.TargetPrefix)
}

Desativar o logging para um bucket

Exclua as configurações e desative o logging para um bucket com o código de exemplo a seguir:

package main

import (
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create an OSSClient instance. 
        // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Specify the name of the bucket. Example: examplebucket. 
	bucketName := "examplebucket"

	// Disable logging for the bucket. 
	err = client.DeleteBucketLogging(bucketName)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}

Referências