Tous les produits
Search
Centre de documentation

Object Storage Service:Stockage des journaux (SDK Python V2)

Dernière mise à jour :Aug 18, 2026

L'accès à OSS génère de nombreux journaux d'accès. Utilisez la fonctionnalité de stockage des journaux pour enregistrer ces journaux sous forme de fichiers dans un bucket spécifié. Les fichiers de journal sont générés toutes les heures selon une convention de nommage fixe.

Précautions

  • Le code exemple de cette rubrique utilise l'ID de région Chine (Hangzhou) cn-hangzhou à titre d'exemple. Par défaut, un endpoint public est utilisé. Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les correspondances entre les régions OSS et les endpoints, consultez Régions et endpoints OSS.

  • Pour activer le stockage des journaux, vous devez disposer de l'autorisation oss:PutBucketLogging. Pour consulter la configuration du stockage des journaux, vous devez disposer de l'autorisation oss:GetBucketLogging. Pour désactiver le stockage des journaux, vous devez disposer de l'autorisation oss:DeleteBucketLogging. Pour plus d'informations, consultez Accorder des autorisations personnalisées à un utilisateur RAM.

Définitions des méthodes

Activer le stockage des journaux

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

Consulter la configuration du stockage des journaux

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

Désactiver le stockage des journaux

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

Paramètres de requête

Paramètre

Type

Description

request

PutBucketLoggingRequest

Les paramètres de la requête. Pour plus d'informations, consultez PutBucketLoggingRequest

GetBucketLoggingRequest

Les paramètres de la requête. Pour plus d'informations, consultez GetBucketLoggingRequest

DeleteBucketLoggingRequest

Les paramètres de la requête. Pour plus d'informations, consultez DeleteBucketLoggingRequest

Valeurs de retour

Type

Description

PutBucketLoggingResult

La valeur de retour. Pour plus d'informations, consultez PutBucketLoggingResult

GetBucketLoggingResult

La valeur de retour. Pour plus d'informations, consultez GetBucketLoggingResult

DeleteBucketLoggingResult

La valeur de retour. Pour plus d'informations, consultez DeleteBucketLoggingResult

Pour la définition complète de l'activation du stockage des journaux, consultez put_bucket_logging.

Pour la définition complète de la consultation de la configuration du stockage des journaux, consultez get_bucket_logging.

Pour la définition complète de la désactivation du stockage des journaux, consultez delete_bucket_logging.

Exemples

Activer le stockage des journaux

L'exemple de code suivant montre comment activer le stockage des journaux.

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.

Consulter la configuration du stockage des journaux

L'exemple de code suivant montre comment consulter la configuration du stockage des journaux.

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.

Désactiver le stockage des journaux

L'exemple de code suivant montre comment désactiver le stockage des journaux.

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.

Configurer des champs de journal définis par l'utilisateur

Appelez l'opération PutUserDefinedLogFieldsConfig pour personnaliser le champ user_defined_log_fields dans les journaux en temps réel d'un bucket. Ce champ permet d'enregistrer des en-têtes de requête ou des paramètres de requête spécifiques pour une analyse ultérieure des requêtes.

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

Interroger les champs de journal définis par l'utilisateur

Appelez l'opération GetUserDefinedLogFieldsConfig pour obtenir la configuration personnalisée du champ user_defined_log_fields dans les journaux en temps réel d'un 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()

Supprimer les champs de journal définis par l'utilisateur

Appelez l'opération DeleteUserDefinedLogFieldsConfig pour supprimer la configuration personnalisée du champ user_defined_log_fields dans les journaux en temps réel d'un 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()