Todos os produtos
Search
Central de documentação

Object Storage Service:Armazenamento de logs (Python SDK V2)

Última atualização: Jul 03, 2026

O acesso ao OSS gera diversos logs de acesso. Use o recurso de armazenamento de logs para salvar esses registros como arquivos de log em um bucket especificado. Os arquivos são gerados a cada hora, seguindo uma convenção de nomenclatura fixa.

Precauções

  • Os códigos de exemplo deste tópico usam o ID da região China (Hangzhou) cn-hangzhou. Por padrão, o sistema usa um endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre os mapeamentos entre regiões e endpoints do OSS, consulte Regiões e endpoints do OSS.

  • Para ativar o armazenamento de logs, você precisa da permissão oss:PutBucketLogging. Para visualizar a configuração de armazenamento de logs, é necessária a permissão oss:GetBucketLogging. Para desativar o armazenamento de logs, você precisa da permissão oss:DeleteBucketLogging. Para obter mais informações, consulte Conceder permissões personalizadas a um usuário RAM.

Definições de métodos

Ative o armazenamento de logs

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

Visualize a configuração de armazenamento de logs

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

Desative o armazenamento de logs

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

Parâmetros da solicitação

Parâmetro

Tipo

Descrição

request

PutBucketLoggingRequest

Parâmetros da solicitação. Para obter mais informações, consulte PutBucketLoggingRequest

GetBucketLoggingRequest

Parâmetros da solicitação. Para obter mais informações, consulte GetBucketLoggingRequest

DeleteBucketLoggingRequest

Parâmetros da solicitação. Para obter mais informações, consulte DeleteBucketLoggingRequest

Valores de retorno

Tipo

Descrição

PutBucketLoggingResult

Valor de retorno. Para obter mais informações, consulte PutBucketLoggingResult

GetBucketLoggingResult

Valor de retorno. Para obter mais informações, consulte GetBucketLoggingResult

DeleteBucketLoggingResult

Valor de retorno. Para obter mais informações, consulte DeleteBucketLoggingResult

Para obter a definição completa sobre como ativar o armazenamento de logs, consulte put_bucket_logging.

Para obter a definição completa sobre como visualizar a configuração de armazenamento de logs, consulte get_bucket_logging.

Para obter a definição completa sobre como desativar o armazenamento de logs, consulte delete_bucket_logging.

Exemplos

Ative o armazenamento de logs

O código de exemplo a seguir mostra como ativar o armazenamento de logs.

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.

Visualize a configuração de armazenamento de logs

O código de exemplo a seguir mostra como visualizar a configuração de armazenamento de logs.

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.

Desative o armazenamento de logs

O código de exemplo a seguir mostra como desativar o armazenamento de logs.

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 campos de log definidos pelo usuário

Chame a operação PutUserDefinedLogFieldsConfig para personalizar o campo user_defined_log_fields nos logs em tempo real de um bucket. Você pode registrar cabeçalhos de solicitação ou parâmetros de consulta específicos nesse campo para analisar as solicitações posteriormente.

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()

Consultar campos de log definidos pelo usuário

Chame a operação GetUserDefinedLogFieldsConfig para obter a configuração personalizada do campo user_defined_log_fields nos logs em tempo real de um 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()

Exclua campos de log definidos pelo usuário

Chame a operação DeleteUserDefinedLogFieldsConfig para excluir a configuração personalizada do campo user_defined_log_fields nos logs em tempo real de um 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()