O Object Storage Service (OSS) gera logs de acesso para registrar o acesso aos recursos armazenados em buckets do OSS. Após a ativação do logging de um bucket, o OSS gera logs de acesso a cada hora com base em regras de nomenclatura predefinidas e os armazena no bucket especificado.
Observações de uso
O código de exemplo neste tópico usa o ID da região
cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o endpoint público acessa recursos em um bucket. Para acessar recursos do bucket a partir de outros serviços da Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para obter uma lista de regiões e endpoints do OSS, consulte Regiões e endpoints.Para ativar o logging de um bucket, é necessária a permissão
oss:PutBucketLogging. Para consultar as configurações de logging de um bucket, é necessária a permissãooss:GetBucketLogging. Para desativar o logging de um bucket, é necessária a permissãooss:DeleteBucketLogging. Para mais informações sobre como conceder permissões, consulte Conceder uma política personalizada.
Exemplos
Ative logging para um bucket
O código de exemplo a seguir ativa o logging para um bucket:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define command-line options (with their descriptions and requirements).
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region of the bucket.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint for accessing OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
];
// Generate a long option list.
$longopts = \array_map(function ($key) {
return "$key:"; // Each key is followed by a colon, indicating that they require a value.
}, array_keys($optsdesc));
// Parse command-line options.
$options = getopt("", $longopts);
// Check whether required options are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Indicate that a required option is missing.
exit(1);
}
}
// Get and use parsed option values.
$region = $options["region"]; // The region of the bucket.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Set the region.
$cfg->setRegion($region);
// If an endpoint is provided, use the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a PutBucketLoggingRequest for enabling logging for the bucket.
$request = new Oss\Models\PutBucketLoggingRequest(
bucket: $bucket, // The name of the bucket.
bucketLoggingStatus: new Oss\Models\BucketLoggingStatus(
loggingEnabled: new Oss\Models\LoggingEnabled(
targetBucket: $bucket, // The destination bucket for stroring log objects.
targetPrefix: 'log/' // The prefix of log object names.
)
)
);
// Call the putBucketLogging method to enable logging for the bucket.
$result = $client->putBucketLogging($request);
// Display the reuslt.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
'request id:' . $result->requestId // The request ID.
);
Consultar as configurações de logging de um bucket
O código de exemplo a seguir consulta as configurações de logging de um bucket:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define command-line options (with their descriptions and requirements).
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region of the bucket.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint for accessing OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
];
// Generate a long option list.
$longopts = \array_map(function ($key) {
return "$key:"; // Each key is followed by a colon, indicating that they require a value.
}, array_keys($optsdesc));
// Parse command-line options.
$options = getopt("", $longopts);
// Check whether required options are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Indicate that a required option is missing.
exit(1);
}
}
// Get and use parsed option values.
$region = $options["region"]; // The region of the bucket.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Set the region.
$cfg->setRegion($region);
// If an endpoint is provided, use the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a GetBucketLoggingRequest for querying logging settings.
$request = new Oss\Models\GetBucketLoggingRequest(
bucket: $bucket // The name of the bucket.
);
// Call the getBucketLogging method to query logging settings.
$result = $client->getBucketLogging($request);
// Display the reuslt.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
'request id:' . $result->requestId . PHP_EOL . // The request ID.
'logging status:' . var_export($result->bucketLoggingStatus, true) . PHP_EOL // The status of logging for the bucket.
);
Desativar logging para um bucket
O código de exemplo a seguir desativa o logging para um bucket:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define command-line options (with their descriptions and requirements).
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region of the bucket.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint for accessing OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
];
// Generate a long option list.
$longopts = \array_map(function ($key) {
return "$key:"; // Each key is followed by a colon, indicating that they require a value.
}, array_keys($optsdesc));
// Parse command-line options.
$options = getopt("", $longopts);
// Check whether required options are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Indicate that a required option is missing.
exit(1);
}
}
// Get and use parsed option values.
$region = $options["region"]; // The region of the bucket.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Set the region.
$cfg->setRegion($region);
// If an endpoint is provided, use the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a DeleteBucketLoggingRequest for deleting the logging settings.
$request = new Oss\Models\DeleteBucketLoggingRequest(
bucket: $bucket // The name of the bucket.
);
// Call the deleteBucketLogging method to delete logging settings for the bucket.
$result = $client->deleteBucketLogging($request);
// Display the reuslt.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
'request id:' . $result->requestId // The request ID.
);
Configure 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 das suas requisições. O código de exemplo a seguir configura campos de log personalizados para um bucket:
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define command-line options (with their descriptions and requirements).
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region of the bucket.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint for accessing OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
];
$longopts = array_map(function ($key) { return "$key:"; }, array_keys($optsdesc));
$options = getopt("", $longopts);
// Check whether required options are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help";
exit(1);
}
}
$region = $options["region"];
$bucket = $options["bucket"];
// Load the AccessKey pair from environment variables. Make sure that environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET exist.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Configure parameter settings for the OSS client.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // The region of the bucket.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Set the endpoint.
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a PutUserDefinedLogFieldsConfigRequest for configuring custom log fields.
$request = new Oss\Models\PutUserDefinedLogFieldsConfigRequest(
bucket: $bucket,
userDefinedLogFieldsConfiguration: new Oss\Models\UserDefinedLogFieldsConfiguration(
new Oss\Models\LoggingParamSet(parameters: ['param1', 'params2']), // Custom query parameters.
new Oss\Models\LoggingHeaderSet(headers: ['header1', 'header2']) // Custom request headers.
)
);
// Configure custom log fields.
$result = $client->putUserDefinedLogFieldsConfig($request);
// Display the status code and request ID.
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId
);
Consultar configurações de campos de log personalizados
Chame a operação GetUserDefinedLogFieldsConfig para consultar as definições de user_defined_log_fields. O código de exemplo a seguir consulta as configurações de campos de log personalizados de um bucket:
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define command-line options (with their descriptions and requirements).
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region of the bucket.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint for accessing OSS. Endpoint format: https://oss-<region>.aliyuncs.com
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
];
$longopts = array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Generate a long option list.
$options = getopt("", $longopts); // Parse command-line options.
// Check whether required options are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help";
exit(1);
}
}
$region = $options["region"]; // Get and use the parsed region.
$bucket = $options["bucket"]; // Get and use the parsed bucket name.
// Load the AccessKey pair from environment variables. Make sure that environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET exist.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Set the credential provider.
// Configure parameter settings for the OSS client.
$cfg = Oss\Config::loadDefault(); // Load the default configuration.
$cfg->setCredentialsProvider($credentialsProvider); // Bind to the specified credential provider.
$cfg->setRegion($region); // Set the region of the bucket.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the provided endpoint.
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a GetUserDefinedLogFieldsConfigRequest for querying custom log field settings.
$request = new Oss\Models\GetUserDefinedLogFieldsConfigRequest(bucket: $bucket); // The name of the bucket.
// Call the getUserDefinedLogFieldsConfig operation to query custom log field settings.
$result = $client->getUserDefinedLogFieldsConfig($request);
// Display the status code, request ID, and
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId . PHP_EOL .
'user defined log fields config:' . var_export($result->userDefinedLogFieldsConfiguration, true) // Use var_export to create a string representation of the object.
);
Exclua 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 de um bucket:
<?php
require_once __DIR__ . '/../vendor/autoload.php'; // Include the autoload file to load dependencies.
use AlibabaCloud\Oss\V2 as Oss; // Import the OSS library.
$optsdesc = [ // Define command-line options.
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region of the bucket.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint for accessing OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket.
];
$longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Generate a long option list.
$options = getopt("", $longopts); // Parse command-line options.
// Check whether required options are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help";
exit(1);
}
}
$region = $options["region"]; // Get and use the parsed region.
$bucket = $options["bucket"]; // Get and use the parsed bucket name.
// Load the AccessKey pair from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Set the credential provider.
// Initialize the client.
$cfg = Oss\Config::loadDefault(); // Load the default configuration.
$cfg->setCredentialsProvider($credentialsProvider); // Bind to the credential provider.
$cfg->setRegion($region); // Set the region.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // (Optional) Set the endpoint.
}
$client = new Oss\Client($cfg); // Create an OSS client instance.
$request = new Oss\Models\DeleteUserDefinedLogFieldsConfigRequest(bucket: $bucket); // Create a request for deleting custom log field settings.
$result = $client->deleteUserDefinedLogFieldsConfig($request); // Delete the settings.
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
'request id:' . $result->requestId // The request ID.
);
Documentação relacionada
Para mais detalhes sobre a operação de API que ativa o logging de um bucket, consulte PutBucketLogging.
Para obter informações sobre a operação de API que consulta as configurações de logging de um bucket, consulte GetBucketLogging.
Para mais detalhes sobre a operação de API que desativa o logging de um bucket, consulte DeleteBucketLogging.
Para mais detalhes sobre a operação de API que configura campos de log personalizados, consulte PutUserDefinedLogFieldsConfig.
Para mais detalhes sobre a operação de API que consulta configurações de campos de log personalizados, consulte GetUserDefinedLogFieldsConfig.
Para mais detalhes sobre a operação de API que exclui configurações de campos de log personalizados, consulte DeleteUserDefinedLogFieldsConfig.