All Products
Search
Document Center

Object Storage Service:Log storage (Python SDK V2)

Last Updated:Aug 01, 2025

Accessing OSS generates numerous access logs. You can use the log storage feature to save these logs as log files in a specified bucket. The log files are generated hourly based on a fixed naming convention.

Precautions

  • The sample code in this topic uses the China (Hangzhou) region ID cn-hangzhou as an example. By default, a public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region, you must use an internal endpoint. For more information about the mappings between OSS regions and endpoints, see OSS regions and endpoints.

  • To enable log storage, you must have the oss:PutBucketLogging permission. To view the log storage configuration, you must have the oss:GetBucketLogging permission. To disable log storage, you must have the oss:DeleteBucketLogging permission. For more information, see Grant custom permissions to a RAM user.

Method definitions

Enable log storage

put_bucket_logging(request: PutBucketLoggingRequest, **kwargs) → PutBucketLoggingResult

View the log storage configuration

get_bucket_logging(request: GetBucketLoggingRequest, **kwargs) → GetBucketLoggingResult

Disable log storage

delete_bucket_logging(request: DeleteBucketLoggingRequest, **kwargs) → DeleteBucketLoggingResult

Request parameters

Parameter

Type

Description

request

PutBucketLoggingRequest

The request parameters. For more information, see PutBucketLoggingRequest

GetBucketLoggingRequest

The request parameters. For more information, see GetBucketLoggingRequest

DeleteBucketLoggingRequest

The request parameters. For more information, see DeleteBucketLoggingRequest

Return values

Type

Description

PutBucketLoggingResult

The return value. For more information, see PutBucketLoggingResult

GetBucketLoggingResult

The return value. For more information, see GetBucketLoggingResult

DeleteBucketLoggingResult

The return value. For more information, see DeleteBucketLoggingResult

For the complete definition of enabling log storage, see put_bucket_logging.

For the complete definition of viewing the log storage configuration, see get_bucket_logging.

For the complete definition of disabling log storage, see delete_bucket_logging.

Examples

Enable log storage

The following sample code shows how to enable log storage.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: set access logging for a bucket.
parser = argparse.ArgumentParser(description="put bucket logging sample")

# Define command-line arguments, including the required region, source bucket name, endpoint, destination bucket name, and an optional log object prefix.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the source bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--target_bucket', help='The bucket that stores access logs', required=True)
parser.add_argument('--target_prefix', help='The prefix of the log objects. This parameter can be left empty.', default='')

def main():
    # Parse command-line arguments to obtain user-input values.
    args = parser.parse_args()

    # Load access credential information from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default SDK configurations and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client for interacting with OSS.
    client = oss.Client(cfg)

    # Send a request to configure access logging for the specified bucket.
    result = client.put_bucket_logging(oss.PutBucketLoggingRequest(
            bucket=args.bucket,  # The name of the source bucket.
            bucket_logging_status=oss.BucketLoggingStatus(
                logging_enabled=oss.LoggingEnabled(
                    target_bucket=args.target_bucket,  # The name of the destination bucket that stores access logs.
                    target_prefix=args.target_prefix,  # The prefix of log objects. This parameter can be an empty string.
                ),
            ),
    ))

    # Print the status code and request ID of the operation result to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
    )

# When this script is directly executed, call the main function to start processing the logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts from here.

View the log storage configuration

The following sample code shows how to view the log storage configuration.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: obtain the access logging configuration of a bucket.
parser = argparse.ArgumentParser(description="get bucket logging sample")

# Define command-line arguments, including the required region, bucket name, and endpoint.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line arguments to obtain user-input values.
    args = parser.parse_args()

    # Load access credential information from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default SDK configurations and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client for interacting with OSS.
    client = oss.Client(cfg)

    # Send a request to obtain the details of the access logging configuration for the specified bucket.
    result = client.get_bucket_logging(oss.GetBucketLoggingRequest(
            bucket=args.bucket,  # The name of the bucket.
    ))

    # Print the status code and request ID of the operation result to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' target bucket: {result.bucket_logging_status.logging_enabled.target_bucket if result.bucket_logging_status and result.bucket_logging_status.logging_enabled else "Not set"},'  # The name of the destination bucket that stores access logs. If this parameter is not set, "Not set" is displayed.
          f' target prefix: {result.bucket_logging_status.logging_enabled.target_prefix if result.bucket_logging_status and result.bucket_logging_status.logging_enabled else "Not set"},'  # The prefix of log objects. If this parameter is not set, "Not set" is displayed.
    )

# When this script is directly executed, call the main function to start processing the logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts from here.

Disable log storage

The following sample code shows how to disable log storage.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: delete the access logging configuration of a bucket.
parser = argparse.ArgumentParser(description="delete bucket logging sample")

# Define command-line arguments, including the required region, bucket name, and endpoint.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line arguments to obtain user-input values.
    args = parser.parse_args()

    # Load access credential information from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default SDK configurations and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client for interacting with OSS.
    client = oss.Client(cfg)

    # Send a request to delete the access logging configuration of the specified bucket.
    result = client.delete_bucket_logging(oss.DeleteBucketLoggingRequest(
            bucket=args.bucket,  # The name of the bucket.
    ))

    # Print the status code and request ID of the operation result to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
    )

# When this script is directly executed, call the main function to start processing the logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts from here.

Configure user-defined log fields

You can call the PutUserDefinedLogFieldsConfig operation to customize the user_defined_log_fields field in the real-time logs of a bucket. You can record specific request headers or query parameters in this field for subsequent request analysis.

import argparse
import alibabacloud_oss_v2 as oss  # Import the Alibaba Cloud OSS SDK.

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put user defined log fields config sample")

# Define command-line arguments.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')


def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Use environment variables to load access credentials (AccessKey ID and AccessKey secret).
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations and set the credentials provider, region, and endpoint.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client.
    client = oss.Client(cfg)

    # Construct a PutUserDefinedLogFieldsConfig request object.
    result = client.put_user_defined_log_fields_config(
        oss.PutUserDefinedLogFieldsConfigRequest(
            bucket=args.bucket,  # Specify the name of the destination bucket.
            user_defined_log_fields_configuration=oss.UserDefinedLogFieldsConfiguration(
                header_set=oss.LoggingHeaderSet(
                    headers=['header1', 'header2'],  # The HTTP headers that you want to record in custom logs.
                ),
                param_set=oss.LoggingParamSet(
                    parameters=['parameter1', 'parameter2'],  # The URL parameters that you want to record in custom logs.
                ),
            ),
        )
    )

    # Print the status code and request ID in the request result to debug or confirm whether the operation is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id}')


if __name__ == "__main__":
    main()

Query user-defined log fields

You can call the GetUserDefinedLogFieldsConfig operation to obtain the custom configuration of the user_defined_log_fields field in the real-time logs of a bucket.

import argparse
import alibabacloud_oss_v2 as oss  # Import the Alibaba Cloud OSS SDK.


# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="get user defined log fields config sample")

# Define command-line arguments.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')


def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Use environment variables to load access credentials (AccessKey ID and AccessKey secret).
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations and set the credentials provider, region, and endpoint.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client.
    client = oss.Client(cfg)

    # Construct a GetUserDefinedLogFieldsConfig request object.
    result = client.get_user_defined_log_fields_config(
        oss.GetUserDefinedLogFieldsConfigRequest(
            bucket=args.bucket,  # Specify the name of the destination bucket.
        ),
    )

    # Print the status code, request ID, and custom log field configuration in the request result.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' header set: {result.user_defined_log_fields_configuration.header_set},'
          f' param set: {result.user_defined_log_fields_configuration.param_set},'
    )


if __name__ == "__main__":
    main()

Delete user-defined log fields

You can call the DeleteUserDefinedLogFieldsConfig operation to delete the custom configuration of the user_defined_log_fields field in the real-time logs of a bucket.

import argparse
import alibabacloud_oss_v2 as oss  # Import the Alibaba Cloud OSS SDK module.


# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="delete user defined log fields config sample")

# Define command-line arguments.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')


def main():
    # Parse command-line arguments.
    args = parser.parse_args()

    # Use environment variables to load access credentials (AccessKey ID and AccessKey secret).
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations and set the credentials provider, region, and endpoint.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize an OSS client instance.
    client = oss.Client(cfg)

    # Construct a DeleteUserDefinedLogFieldsConfig request object.
    result = client.delete_user_defined_log_fields_config(
        oss.DeleteUserDefinedLogFieldsConfigRequest(
            bucket=args.bucket,  # Specify the name of the destination bucket.
        ),
    )

    # Print the status code and request ID in the request result.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id}'
    )


if __name__ == "__main__":
    main()