Todos los productos
Search
Centro de documentos

Object Storage Service:Registros con OSS SDK for PHP 2.0

Última actualización: Sep 03, 2026

Object Storage Service (OSS) genera registros de acceso para documentar las solicitudes a los recursos almacenados en buckets de OSS. Al habilitar el registro de un bucket, OSS crea registros de acceso cada hora según reglas de nomenclatura predefinidas y los almacena en el bucket especificado.

Notas de uso

  • El código de ejemplo de este tema usa el ID de región cn-hangzhou correspondiente a la región China (Hangzhou). De forma predeterminada, se usa el endpoint público para acceder a los recursos de un bucket. Si necesita acceder a los recursos del bucket desde otros servicios de Alibaba Cloud en la misma región donde se encuentra el bucket, use un endpoint interno. Para consultar la lista de regiones y endpoints de OSS, consulte Regions and endpoints.

  • Para habilitar el registro de un bucket, debe contar con el permiso oss:PutBucketLogging. Para consultar la configuración de registro de un bucket, requiere el permiso oss:GetBucketLogging. Para deshabilitar el registro de un bucket, es necesario tener el permiso oss:DeleteBucketLogging. Para obtener más información sobre cómo otorgar permisos, consulte Grant a custom policy.

Ejemplos

Habilitar el registro de un bucket

El siguiente código de ejemplo habilita el registro de 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.
);

Consultar la configuración de registro de un bucket

El siguiente código de ejemplo consulta la configuración de registro de 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.
);

Deshabilitar el registro de un bucket

El siguiente código de ejemplo deshabilita el registro de 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.
);

Configurar campos de registro personalizados

Llame a la operación PutUserDefinedLogFieldsConfig para configurar el campo user_defined_log_fields, que contiene campos de registro personalizados. Estos campos pueden incluir encabezados de solicitud o parámetros de consulta relevantes para su análisis posterior. El siguiente código de ejemplo configura campos de registro personalizados para 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
);

Consultar la configuración de campos de registro personalizados

Llame a la operación GetUserDefinedLogFieldsConfig para consultar la configuración de user_defined_log_fields. El siguiente código de ejemplo consulta la configuración de campos de registro personalizados de 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.
);

Eliminar la configuración de campos de registro personalizados

Llame a la operación DeleteUserDefinedLogFieldsConfig para eliminar la configuración personalizada de user_defined_log_fields. El siguiente código de ejemplo elimina la configuración de campos de registro personalizados de 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.
);

Documentación relacionada

  • Para obtener más información sobre la operación de API que habilita el registro de un bucket, consulte PutBucketLogging.

  • Para obtener más información sobre la operación de API que consulta la configuración de registro de un bucket, consulte GetBucketLogging.

  • Para obtener más información sobre la operación de API que deshabilita el registro de un bucket, consulte DeleteBucketLogging.

  • Para obtener más información sobre la operación de API que configura campos de registro personalizados, consulte PutUserDefinedLogFieldsConfig.

  • Para obtener más información sobre la operación de API que consulta la configuración de campos de registro personalizados, consulte GetUserDefinedLogFieldsConfig.

  • Para obtener más información sobre la operación de API que elimina la configuración de campos de registro personalizados, consulte DeleteUserDefinedLogFieldsConfig.