O registro de acesso do Object Storage Service (OSS) captura informações detalhadas sobre as solicitações aos seus buckets. Após você ativar o log para um bucket de origem, o OSS gera e entrega automaticamente arquivos de log a cada hora em um bucket de destino especificado, seguindo uma convenção de nomenclatura predefinida.
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Para 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 Regiões e endpoints.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização (C# SDK V1).
Gerenciar logs de um bucket exige permissões específicas:
oss:PutBucketLoggingpara ativar,oss:GetBucketLoggingpara consultar eoss:DeleteBucketLoggingpara desativar. Para mais detalhes, consulte Conceder uma política personalizada.
Ativar logs para um bucket
O exemplo de código a seguir mostra como ativar o armazenamento de logs para um bucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set the Endpoint. This example uses https://oss-cn-hangzhou.aliyuncs.com, the public Endpoint for the China (Hangzhou) region. For other regions, set the Endpoint to the actual value.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Set the name of the bucket for which to enable log storage, for example, examplebucket.
var bucketName = "examplebucket";
// Set the destination bucket to store the log files. The destination bucket can be the same as or different from the source bucket.
var targetBucketName = "destbucket";
// Set the region where the bucket is located. This example uses cn-hangzhou, which is the ID of the China (Hangzhou) region.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Set the folder where the log files are stored to log/. If you specify this folder, the log files are saved to the specified folder in the destination bucket. If you do not specify this folder, the log files are saved to the root directory of the destination bucket.
var request = new SetBucketLoggingRequest(bucketName, targetBucketName, "log/");
// Enable the log storage feature.
client.SetBucketLogging(request);
Console.WriteLine("Set bucket:{0} Logging succeeded ", bucketName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}. Error message: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error message: {0}", ex.Message);
}
Consultar as configurações de log de um bucket
O exemplo de código a seguir mostra como consultar as configurações de log de um bucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set the Endpoint. This example uses https://oss-cn-hangzhou.aliyuncs.com, the public Endpoint for the China (Hangzhou) region. For other regions, set the Endpoint to the actual value.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Set the bucket name, for example, examplebucket.
var bucketName = "examplebucket";
// Set the region where the bucket is located. This example uses cn-hangzhou, which is the ID of the China (Hangzhou) region.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// View the log storage configuration.
var result = client.GetBucketLogging(bucketName);
Console.WriteLine("Get bucket:{0} Logging succeeded, prefix:{1}", bucketName, result.TargetPrefix);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}. Error message: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error message: {0}", ex.Message);
}
Desativar logs para um bucket
O exemplo de código a seguir mostra como desativar o armazenamento de logs para um bucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set the Endpoint. This example uses https://oss-cn-hangzhou.aliyuncs.com, the public Endpoint for the China (Hangzhou) region. For other regions, set the Endpoint to the actual value.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Set the bucket name, for example, examplebucket.
var bucketName = "examplebucket";
// Set the region where the bucket is located. This example uses cn-hangzhou, which is the ID of the China (Hangzhou) region.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Disable the log storage feature.
client.DeleteBucketLogging(bucketName);
Console.WriteLine("Delete bucket:{0} Logging succeeded ", bucketName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}. Error message: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error message: {0}", ex.Message);
}
Referências
Para visualizar o código completo de armazenamento de logs, consulte o exemplo no GitHub.