Accessing OSS generates many access logs. You can use the log storage feature to create hourly log files based on a fixed naming convention and write them to a specified bucket.
Usage notes
The sample code in this topic uses the China (Hangzhou) region (
cn-hangzhou) as an example. The public endpoint is used by default. To access OSS from other Alibaba Cloud products in the same region, use an internal endpoint. For more information about the regions and endpoints that OSS supports, see Regions and endpoints for OSS.To enable log storage, you must have the
oss:PutBucketLoggingpermission. To view log storage configurations, you must have theoss:GetBucketLoggingpermission. To disable log storage, you must have theoss:DeleteBucketLoggingpermission. For more information, see Attach a custom policy to a RAM user.
Examples
Enable log storage
The following code provides an example of how to enable the log storage feature.
<?php
// Include the autoload file to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the descriptions of command-line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint that other services can use to access OSS. This parameter is optional.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket. This parameter is required.
];
// Generate a long option list to parse command-line arguments.
$longopts = \array_map(function ($key) {
return "$key:"; // A colon is added to the end of each parameter to indicate that the parameter requires a value.
}, array_keys($optsdesc));
// Parse command-line arguments.
$options = getopt("", $longopts);
// Check whether required parameters 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"; // A message is returned to indicate that a required parameter is missing.
exit(1);
}
}
// Obtain the values of command-line arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations 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, set the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request object to configure the log storage feature 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 log storage.
targetPrefix: 'log/' // The prefix of log files.
)
)
);
// Call the putBucketLogging method to configure the log storage feature for the bucket.
$result = $client->putBucketLogging($request);
// Print the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId // The unique request ID.
);
View log storage configurations
The following code provides an example of how to view log storage configurations.
<?php
// Include the autoload file to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the descriptions of command-line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint that other services can use to access OSS. This parameter is optional.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket. This parameter is required.
];
// Generate a long option list to parse command-line arguments.
$longopts = \array_map(function ($key) {
return "$key:"; // A colon is added to the end of each parameter to indicate that the parameter requires a value.
}, array_keys($optsdesc));
// Parse command-line arguments.
$options = getopt("", $longopts);
// Check whether required parameters 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"; // A message is returned to indicate that a required parameter is missing.
exit(1);
}
}
// Obtain the values of command-line arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations 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, set the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request object to obtain the log storage configurations of the bucket.
$request = new Oss\Models\GetBucketLoggingRequest(
bucket: $bucket // The name of the bucket.
);
// Call the getBucketLogging method to obtain the log storage configurations of the bucket.
$result = $client->getBucketLogging($request);
// Print the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL . // The unique request ID.
'logging status:' . var_export($result->bucketLoggingStatus, true) . PHP_EOL // The configuration status of the log storage feature for the bucket.
);
Disable log storage
The following code provides an example of how to disable the log storage feature.
<?php
// Include the autoload file to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the descriptions of command-line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint that other services can use to access OSS. This parameter is optional.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket. This parameter is required.
];
// Generate a long option list to parse command-line arguments.
$longopts = \array_map(function ($key) {
return "$key:"; // A colon is added to the end of each parameter to indicate that the parameter requires a value.
}, array_keys($optsdesc));
// Parse command-line arguments.
$options = getopt("", $longopts);
// Check whether required parameters 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"; // A message is returned to indicate that a required parameter is missing.
exit(1);
}
}
// Obtain the values of command-line arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations 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, set the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request object to delete the log storage configurations of the bucket.
$request = new Oss\Models\DeleteBucketLoggingRequest(
bucket: $bucket // The name of the bucket.
);
// Call the deleteBucketLogging method to delete the log storage configurations of the bucket.
$result = $client->deleteBucketLogging($request);
// Print the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId // The unique request ID.
);
Configure user-defined log fields
You can call the PutUserDefinedLogFieldsConfig operation to configure the user_defined_log_fields field for the real-time logs of a bucket. This lets you record information from the request headers or query parameters of OSS requests to this field for later analysis.
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the descriptions of command-line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint that other services can use to access OSS. This parameter is optional.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket. This parameter is required.
];
$longopts = array_map(function ($key) { return "$key:"; }, array_keys($optsdesc));
$options = getopt("", $longopts);
// Verify that required parameters are specified.
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. You must configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables in advance.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Configure the parameters for the OSS client.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Set the endpoint. Example: https://oss-cn-hangzhou.aliyuncs.com.
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request to configure user-defined log fields.
$request = new Oss\Models\PutUserDefinedLogFieldsConfigRequest(
bucket: $bucket,
userDefinedLogFieldsConfiguration: new Oss\Models\UserDefinedLogFieldsConfiguration(
new Oss\Models\LoggingParamSet(parameters: ['param1', 'params2']), // Custom log parameters.
new Oss\Models\LoggingHeaderSet(headers: ['header1', 'header2']) // Custom log headers.
)
);
// Execute the operation to configure user-defined log fields.
$result = $client->putUserDefinedLogFieldsConfig($request);
// Print the status code and request ID of the operation result.
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId
);
Query user-defined log fields
You can call the GetUserDefinedLogFieldsConfig operation to retrieve the custom configurations of the user_defined_log_fields field in the real-time logs of a bucket.
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the descriptions of command-line arguments, which must include the bucket region, endpoint, and name.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region is required. Specify the region where the bucket is located. Example: cn-hangzhou.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint is optional. The endpoint must be in the https://oss-<region>.aliyuncs.com format.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket. This parameter is required.
];
$longopts = array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Convert the parameters to the command-line option format.
$options = getopt("", $longopts); // Parse command-line arguments.
// Verify that required parameters are specified. Make sure that the region and bucket parameters are provided.
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"]; // Obtain the value of the region parameter.
$bucket = $options["bucket"]; // Obtain the bucket name.
// Load the AccessKey pair from environment variables. You must configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables in advance.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use the environment variable credential provider.
// Configure the parameters for the OSS client, including the region, credentials, and optional endpoint.
$cfg = Oss\Config::loadDefault(); // Load the default configuration.
$cfg->setCredentialsProvider($credentialsProvider); // Attach the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located. Example: cn-hangzhou.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Set a custom endpoint. Example: https://oss-cn-hangzhou.aliyuncs.com.
}
// Create an OSS client instance to call API operations.
$client = new Oss\Client($cfg);
// Create a request to obtain the configurations of user-defined log fields.
$request = new Oss\Models\GetUserDefinedLogFieldsConfigRequest(bucket: $bucket); // Specify the name of the bucket that you want to query.
// Execute the operation to obtain the configurations of user-defined log fields. The oss:GetUserDefinedLogFieldsConfig permission is required.
$result = $client->getUserDefinedLogFieldsConfig($request); // Call the API operation to obtain the configuration information.
// Print the status code, request ID, and configuration details of the operation result.
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 print the structure of the configuration object.
);
Delete user-defined log fields
You can call the DeleteUserDefinedLogFieldsConfig operation to delete the custom configurations of the user_defined_log_fields field in the real-time logs of a bucket.
<?php
require_once __DIR__ . '/../vendor/autoload.php'; // Load SDK dependencies.
use AlibabaCloud\Oss\V2 as Oss; // Import the OSS PHP SDK namespace.
$optsdesc = [ // Define command-line argument rules.
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // region parameter: The region where the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // Optional endpoint parameter.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required bucket name parameter.
];
$longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Convert the parameters to the command-line format.
$options = getopt("", $longopts); // Parse command-line arguments.
// Parameter verification: Check whether required parameters are specified.
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"]; // Obtain the value of the region parameter.
$bucket = $options["bucket"]; // Obtain the bucket name.
// Load the AccessKey pair from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use environment variable credentials.
// Initialize client configurations.
$cfg = Oss\Config::loadDefault(); // Load the default configuration template.
$cfg->setCredentialsProvider($credentialsProvider); // Attach the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Set a custom endpoint (optional).
}
$client = new Oss\Client($cfg); // Create an OSS client instance.
$request = new Oss\Models\DeleteUserDefinedLogFieldsConfigRequest(bucket: $bucket); // Create a request to delete the configurations.
$result = $client->deleteUserDefinedLogFieldsConfig($request); // Perform the delete operation.
// Print the result information.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
'request id:' . $result->requestId // The unique request ID.
);
References
For more information about enabling log storage, see PutBucketLogging.
For more information about viewing log storage configurations, see GetBucketLogging.
For more information about disabling log storage, see DeleteBucketLogging.
For more information about configuring user-defined log fields, see PutUserDefinedLogFieldsConfig.
For more information about querying user-defined log fields, see GetUserDefinedLogFieldsConfig.
For more information about deleting user-defined log fields, see DeleteUserDefinedLogFieldsConfig.