bucket_logging.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package sample
  2. import (
  3. "fmt"
  4. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  5. )
  6. // BucketLoggingSample shows how to set, get and delete the bucket logging configuration
  7. func BucketLoggingSample() {
  8. // New client
  9. client, err := oss.New(endpoint, accessID, accessKey)
  10. if err != nil {
  11. HandleError(err)
  12. }
  13. // Create the bucket with default parameters
  14. err = client.CreateBucket(bucketName)
  15. if err != nil {
  16. HandleError(err)
  17. }
  18. // Create target bucket to store the logging files.
  19. var targetBucketName = "target-bucket"
  20. err = client.CreateBucket(targetBucketName)
  21. if err != nil {
  22. HandleError(err)
  23. }
  24. // Case 1: Set the logging for the object prefixed with "prefix-1" and save their access logs to the target bucket
  25. err = client.SetBucketLogging(bucketName, targetBucketName, "prefix-1", true)
  26. if err != nil {
  27. HandleError(err)
  28. }
  29. // Case 2: Set the logging for the object prefixed with "prefix-2" and save their logs to the same bucket
  30. // Note: the rule will overwrite other rules if they have same bucket and prefix
  31. err = client.SetBucketLogging(bucketName, bucketName, "prefix-2", true)
  32. if err != nil {
  33. HandleError(err)
  34. }
  35. // Delete the bucket's logging configuration
  36. err = client.DeleteBucketLogging(bucketName)
  37. if err != nil {
  38. HandleError(err)
  39. }
  40. // Case 3: Set the logging without enabling it
  41. err = client.SetBucketLogging(bucketName, targetBucketName, "prefix-3", false)
  42. if err != nil {
  43. HandleError(err)
  44. }
  45. // Get the bucket's logging configuration
  46. gbl, err := client.GetBucketLogging(bucketName)
  47. if err != nil {
  48. HandleError(err)
  49. }
  50. fmt.Println("Bucket Logging:", gbl.LoggingEnabled)
  51. err = client.SetBucketLogging(bucketName, bucketName, "prefix2", true)
  52. if err != nil {
  53. HandleError(err)
  54. }
  55. // Get the bucket's logging configuration
  56. gbl, err = client.GetBucketLogging(bucketName)
  57. if err != nil {
  58. HandleError(err)
  59. }
  60. fmt.Println("Bucket Logging:", gbl.LoggingEnabled)
  61. // Delete the bucket's logging configuration
  62. err = client.DeleteBucketLogging(bucketName)
  63. if err != nil {
  64. HandleError(err)
  65. }
  66. // Delete bucket
  67. err = client.DeleteBucket(bucketName)
  68. if err != nil {
  69. HandleError(err)
  70. }
  71. err = client.DeleteBucket(targetBucketName)
  72. if err != nil {
  73. HandleError(err)
  74. }
  75. fmt.Println("BucketLoggingSample completed")
  76. }