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 les stocke dans le bucket spécifié.
Remarques sur l'utilisation
L'exemple de code de cette rubrique utilise l'ID de région
cn-hangzhoude la région Chine (Hangzhou). Par défaut, le point de terminaison public permet d'accéder aux ressources d'un bucket. Pour accéder aux ressources du bucket depuis d'autres services Alibaba Cloud situés dans la même région, utilisez 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.Pour activer la journalisation d'un bucket, vous devez disposer de l'autorisation
oss:PutBucketLogging. Pour consulter les paramètres de journalisation d'un bucket, vous devez disposer de l'autorisationoss:GetBucketLogging. Pour désactiver la journalisation d'un bucket, vous devez disposer de l'autorisationoss:DeleteBucketLogging. Pour plus d'informations sur l'attribution des autorisations, consultez Accorder une stratégie personnalisée.
Exemples
Activer la journalisation pour un bucket
L'exemple de code suivant active la journalisation pour un 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.
);
Consulter les paramètres de journalisation d'un bucket
L'exemple de code suivant consulte les paramètres de journalisation d'un 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.
);
Désactiver la journalisation pour un bucket
L'exemple de code suivant désactive la journalisation pour un 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.
);
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 :
<?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
);
Consulter les paramètres des champs de journal personnalisés
Appelez l'opération GetUserDefinedLogFieldsConfig pour consulter les paramètres user_defined_log_fields. L'exemple de code suivant consulte les paramètres des champs de journal personnalisés pour un 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.
);
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 :
<?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.
);
Documentation connexe
Pour plus d'informations sur l'opération API qui active la journalisation pour un bucket, consultez PutBucketLogging.
Pour plus d'informations sur l'opération API qui consulte les paramètres de journalisation d'un bucket, consultez GetBucketLogging.
Pour plus d'informations sur l'opération API qui désactive la journalisation pour un bucket, consultez DeleteBucketLogging.
Pour plus d'informations sur l'opération API qui configure des champs de journal personnalisés, consultez PutUserDefinedLogFieldsConfig.
Pour plus d'informations sur l'opération API qui consulte 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.