Tous les produits
Search
Centre de documentation

Object Storage Service:Journalisation via OSS SDK pour Go 2.0

Dernière mise à jour :Aug 18, 2026

Object Storage Service (OSS) génère des journaux d'accès pour enregistrer les accès aux ressources stockées dans les buckets OSS. Une fois la journalisation activée pour un bucket, OSS génère des journaux d'accès toutes les heures selon des règles de nommage prédéfinies, puis stocke ces journaux dans le bucket spécifié.

Remarques sur l'utilisation

  • L'exemple de code présenté dans cette rubrique utilise l'ID de région cn-hangzhou de la région Chine (Hangzhou). Par défaut, le point de terminaison public est utilisé pour accéder aux ressources d'un bucket. Si vous souhaitez accéder aux ressources du bucket depuis d'autres services Alibaba Cloud situés dans la même région que le bucket, nous vous recommandons d'utiliser un point de terminaison interne. Pour obtenir la liste des régions et des points de terminaison OSS, consultez Régions et points de terminaison.

  • Dans cette rubrique, les identifiants d'accès sont récupérés à partir des variables d'environnement. Pour plus d'informations sur la configuration des identifiants d'accès, consultez Configurer les identifiants d'accès (Go SDK V1).

  • Pour activer la journalisation d'un bucket, vous devez disposer de l'autorisation oss:PutBucketLogging. Pour interroger les paramètres de journalisation d'un bucket, vous devez disposer de l'autorisation oss:GetBucketLogging. Pour désactiver la journalisation d'un bucket, vous devez disposer de l'autorisation oss:DeleteBucketLogging. Pour plus d'informations sur l'attribution des autorisations, consultez Accorder une stratégie personnalisée.

Exemple de code

Activer la journalisation

Le code suivant active la journalisation pour 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)
}

Interroger les paramètres de journalisation d'un bucket

Le code suivant interroge les paramètres de journalisation d'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)
}

Désactiver la journalisation d'un bucket

Le code suivant désactive la journalisation d'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)
}

Configurer des champs de journal personnalisés

Appelez l'opération PutUserDefinedLogFieldsConfig pour configurer le champ user_defined_log_fields, qui contient des champs de journal personnalisés. Ces champs peuvent inclure des en-têtes de requête ou des paramètres de requête pertinents pour vos analyses ultérieures. L'exemple de code suivant configure des champs de journal personnalisés pour 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)
}

Interroger les paramètres des champs de journal personnalisés

Appelez l'opération GetUserDefinedLogFieldsConfig pour interroger les paramètres user_defined_log_fields. L'exemple de code suivant interroge les paramètres des champs de journal personnalisés pour 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), // 设置目标 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)
}

Supprimer les paramètres des champs de journal personnalisés

Appelez l'opération DeleteUserDefinedLogFieldsConfig pour supprimer les paramètres user_defined_log_fields personnalisés. L'exemple de code suivant supprime les paramètres des champs de journal personnalisés pour 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)
}

Références

  • Pour plus d'informations sur l'opération API qui active la journalisation d'un bucket, consultez PutBucketLogging.

  • Pour plus d'informations sur l'opération API qui interroge les paramètres de journalisation d'un bucket, consultez GetBucketLogging.

  • Pour plus d'informations sur l'opération API qui désactive la journalisation d'un bucket, consultez DeleteBucketLogging.

  • Pour plus d'informations sur l'opération API qui configure les champs de journal personnalisés, consultez PutUserDefinedLogFieldsConfig.

  • Pour plus d'informations sur l'opération API qui interroge les paramètres des champs de journal personnalisés, consultez GetUserDefinedLogFieldsConfig.

  • Pour plus d'informations sur l'opération API qui supprime les paramètres des champs de journal personnalisés, consultez DeleteUserDefinedLogFieldsConfig.