Tous les produits
Search
Centre de documentation

Object Storage Service:Transfert de journaux

Dernière mise à jour :Aug 08, 2026

Activez la journalisation pour générer des fichiers de journaux d'accès horaires et les stocker dans un compartiment spécifié. Analysez ces journaux avec Log Service ou un cluster Spark.

Remarques sur l'utilisation

  • Si le compartiment source possède un attribut de région, le compartiment cible doit appartenir au même compte et à la même région. Il peut être identique ou différent du compartiment source.

    Lorsque les compartiments source et cible sont identiques, l'opération de transfert de journaux génère des journaux supplémentaires, ce qui crée une boucle. Utilisez des compartiments source et cible différents pour éviter cela.

  • La génération des fichiers de journaux peut prendre jusqu'à 48 heures. Les requêtes peuvent apparaître dans des fichiers de périodes adjacentes ; par conséquent, l'exhaustivité et la ponctualité des journaux pour une période donnée ne sont pas garanties.

  • OSS génère un fichier de journal toutes les heures tant que vous n'avez pas désactivé la journalisation. Supprimez les fichiers de journaux inutiles pour réduire les coûts de stockage.

    Utilisez les règles de cycle de vie basées sur la dernière date de modification pour supprimer périodiquement les fichiers de journaux.

  • Pour éviter toute interruption de service ou contamination des données lors de la configuration du transfert de journaux pour un compartiment avec OSS-HDFS activé, ne définissez pas le Log Prefix sur .dlsdata/.

  • OSS peut ajouter de nouveaux champs aux journaux. Concevez vos outils de traitement des journaux de manière à gérer ces ajouts. Par exemple, le champ ARN du compartiment sera ajouté aux journaux à partir du 17 septembre 2025.

  • Évitez de transférer les journaux vers un compartiment avec ObjectWorm activé. ObjectWorm empêche la suppression des journaux pendant la période de rétention, ce qui entraîne une augmentation constante des coûts de stockage.

Configurer la journalisation

Configurer la journalisation pour un compartiment

Console

  1. Connectez-vous à la console OSS.

  2. Dans le volet de navigation de gauche, cliquez sur Buckets. Sur la page qui s'affiche, cliquez sur le nom du compartiment cible.

  3. Dans le volet de navigation de gauche, choisissez Logging > Logging.

  4. Sur la page Logging, activez Logging, puis configurez les paramètres suivants.

    Paramètre

    Description

    Compartiment cible

    Le compartiment qui stocke les journaux. Par défaut : le compartiment actuel. Sélectionnez un autre compartiment dans la liste déroulante si nécessaire. Le compartiment cible doit appartenir au même compte et à la même région.

    Préfixe de journal

    Le répertoire du compartiment cible pour les fichiers de journaux. Si non spécifié, les journaux vont dans le répertoire racine. Exemple : définir le préfixe sur log/ stocke les journaux dans le répertoire log/.

    Rôle RAM

    Le rôle qu'assume OSS pour écrire les journaux.

    • Rôle de service par défaut (recommandé)

      Crée automatiquement le rôle AliyunOSSLoggingDefaultRole avec les autorisations requises pour tous les compartiments de votre compte. Pour les nouveaux utilisateurs : cliquez sur Authorize Now pour créer et autoriser le rôle.

    • Rôle personnalisé

      Pour limiter les autorisations de journalisation à un compartiment spécifique, créez un rôle personnalisé :

      1. Créer un rôle RAM pour un service Alibaba Cloud approuvé. Lors de la création du rôle, définissez Service approuvé sur Cloud Service et Sélectionner le service approuvé sur OSS.

      2. Créer une stratégie personnalisée à l'aide de l'éditeur de script.

        Chiffrement KMS
        {
              "Version": "1",
              "Statement": [
                {
                  "Effect": "Allow",
                  "Action": [
                    "kms:List*",
                    "kms:Describe*",
                    "kms:GenerateDataKey",
                    "kms:Decrypt"
                  ],
                  "Resource": "*"
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "oss:PutObject",
                    "oss:AbortMultipartUpload"
                  ],
                  "Resource": "acs:oss:*:*:examplebucket/*"
                }
              ]
            }

        Sans chiffrement KMS

        Utilisez cette stratégie pour les compartiments sans chiffrement ou avec un chiffrement côté serveur géré par OSS.

        {
              "Version": "1",
              "Statement": [  
                {
                  "Effect": "Allow",
                  "Action": [
                    "oss:PutObject",
                    "oss:AbortMultipartUpload"
                  ],
                  "Resource": "acs:oss:*:*:examplebucket/*"
                }
              ]
            }
      3. Accorder des autorisations au rôle RAM.

  5. Cliquez sur Save.

Ossutil

Activez la journalisation avec l'interface CLI ossutil. Installez ossutil.

La commande suivante active la journalisation pour examplebucket, en stockant les journaux d'accès dans destBucket avec le préfixe MyLog-.

ossutil api put-bucket-logging --bucket examplebucket --bucket-logging-status "{\"LoggingEnabled\":{\"TargetBucket\":\"destBucket\",\"TargetPrefix\":\"MyLog-\"}}"

put-bucket-logging.

SDK

Configurez la journalisation avec les exemples de SDK suivants. D'autres SDK sont répertoriés dans SDK.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.SetBucketLoggingRequest;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the source bucket for which you want to enable logging. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the name of the destination bucket in which you want to store the log objects. The source bucket and the destination bucket can be the same bucket or different buckets. 
        String targetBucketName = "yourTargetBucketName";
        // Set the directory in which you want to store the log objects to log/. If you specify this parameter, the log objects are stored in the specified directory of the destination bucket. If you do not specify this parameter, the log objects are stored in the root directory of the destination bucket. 
        String targetPrefix = "log/";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // Call the shutdown method to release resources when the OSSClient is no longer in use. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            SetBucketLoggingRequest request = new SetBucketLoggingRequest(bucketName);
            request.setTargetBucket(targetBucketName);
            request.setTargetPrefix(targetPrefix);
            ossClient.setBucketLogging(request);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.  
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "yourEndpoint";
// Specify the name of the source bucket for which you want to enable logging. Example: examplebucket. 
$bucket= "examplebucket";

$option = array();
// Specify the name of the destination bucket in which the log objects are stored. 
$targetBucket = "destbucket";
// Specify the directory in which the log objects are stored. If you specify this parameter, the log objects are stored in the specified directory of the destination bucket. If you do not specify this parameter, the log objects are stored in the root directory of the destination bucket. 
$targetPrefix = "log/";

try {
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    // Enable logging for the source bucket. 
    $ossClient->putBucketLogging($bucket, $targetBucket, $targetPrefix, $option);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");            
const OSS = require('ali-oss')
const client = new OSS({
  // Set region to the region where the bucket is located. For example, for China (Hangzhou), set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this code sample, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Set bucket to the name of your bucket.
  bucket: 'yourbucketname'
});
async function putBucketLogging () {
  try {
     const result = await client.putBucketLogging('bucket-name', 'logs/');
     console.log(result)
  } catch (e) {
    console.log(e)
  }
}
putBucketLogging();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import BucketLogging

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Specify that the generated log objects are stored in the current bucket. 
# Set the directory in which the log objects are stored to log/. If you specify this parameter, the log objects are stored in the specified directory of the bucket. If you do not specify this parameter, the log objects are stored in the root directory of the bucket. 
# Enable logging for the bucket. 
logging = bucket.put_bucket_logging(BucketLogging(bucket.bucket_name, 'log/'))
if logging.status == 200:
    print("Enable access logging")
else:
    print("request_id:", logging.request_id)
    print("resp : ", logging.resp.response)            
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Set the Endpoint. This example uses https://oss-cn-hangzhou.aliyuncs.com, the public Endpoint for the China (Hangzhou) region. For other regions, set the Endpoint to the actual value.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Set the name of the bucket for which to enable log storage, for example, examplebucket.
var bucketName = "examplebucket";
// Set the destination bucket to store the log files. The destination bucket can be the same as or different from the source bucket.
var targetBucketName = "destbucket";
// Set the region where the bucket is located. This example uses cn-hangzhou, which is the ID of the China (Hangzhou) region.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();

// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Set the folder where the log files are stored to log. If you specify this folder, the log files are saved to the specified folder in the destination bucket. If you do not specify this folder, the log files are saved to the root directory of the destination bucket.
    var request = new SetBucketLoggingRequest(bucketName, targetBucketName, "log");
    // Enable the log storage feature.
    client.SetBucketLogging(request);
    Console.WriteLine("Set bucket:{0} Logging succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}. Error message: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error message: {0}", ex.Message);
}
PutBucketLoggingRequest request = new PutBucketLoggingRequest();
// Specify the source bucket for which to enable access logging.
request.setBucketName("yourSourceBucketName");
// Specify the destination bucket to store access logs.
// The destination bucket and the source bucket must be in the same region. The source and destination buckets can be the same or different.
request.setTargetBucketName("yourTargetBucketName");
// Set the folder where the log files are stored.
request.setTargetPrefix("<yourTargetPrefix>");

OSSAsyncTask task = oss.asyncPutBucketLogging(request, new OSSCompletedCallback<PutBucketLoggingRequest, PutBucketLoggingResult>() {
    @Override
    public void onSuccess(PutBucketLoggingRequest request, PutBucketLoggingResult result) {
        OSSLog.logInfo("code::"+result.getStatusCode());
    }

    @Override
    public void onFailure(PutBucketLoggingRequest request, ClientException clientException, ServiceException serviceException) {
         OSSLog.logError("error: "+serviceException.getRawMessage());
    }
});
task.waitUntilFinished();
package main

import (
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create an OSSClient instance. 
        // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Specify the name of the source bucket for which you want to enable logging. Example: examplebucket. 
	bucketName := "examplebucket"
	// Specify the name of the destination bucket in which you want to store the log objects. The source and destination buckets can be the same bucket or different buckets, but they must be located in the same region. 
	targetBucketName := "destbucket"
	// Set the directory in which you want to store the log objects to log/. If you specify this parameter, the log objects are stored in the specified directory of the destination bucket. If you do not specify this parameter, the log objects are stored in the root directory of the destination bucket. 
	targetPrefix := "log/"

	// Enable logging for the bucket. 
	err = client.SetBucketLogging(bucketName, targetBucketName, targetPrefix, true)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set Endpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set Region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the name of the bucket for which you want to enable log storage, for example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Enter the destination bucket to store the log files. The targetBucketName and bucketName can be the same or different. */
    std::string TargetBucketName = "destbucket";
    /* Set the folder where the log files are stored to log/. If you specify this parameter, the log files are saved to the specified folder in the destination bucket. If you do not specify this parameter, the log files are saved to the root directory of the destination bucket. */
    std::string TargetPrefix  ="log/";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region); 

    /* Enable the log storage feature. */
    SetBucketLoggingRequest request(BucketName, TargetBucketName, TargetPrefix);
    auto outcome = client.SetBucketLogging(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketLogging fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. For example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the destination bucket to store the log files. The targetBucketName and bucketName can be the same or different. */
const char *target_bucket_name = "yourTargetBucketName";
/* Set the folder where the log files are stored. If you specify this parameter, the log files are saved to the specified folder in the destination bucket. If you do not specify this parameter, the log files are saved to the root directory of the destination bucket. */
const char *target_logging_prefix = "yourTargetPrefix";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize the aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // You must also configure the following two parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether a CNAME is used. A value of 0 indicates that no CNAME is used. */
    options->config->is_cname = 0;
    /* Set network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method at the program entry to initialize global resources such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* The memory pool (pool) for memory management is equivalent to apr_pool_t. The implementation code is in the apr library. */
    aos_pool_t *pool;
    /* Create a memory pool. The second parameter is NULL, which indicates that the memory pool does not inherit from another memory pool. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information such as the endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate memory to options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client options oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_string_t bucket;
    oss_logging_config_content_t *content;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    aos_str_set(&bucket, bucket_name);
    content = oss_create_logging_rule_content(pool);
    aos_str_set(&content->target_bucket, target_bucket_name);
    aos_str_set(&content->prefix, target_logging_prefix);
    /* Enable access logging for the bucket. */
    resp_status = oss_put_bucket_logging(oss_client_options, &bucket, content, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("put bucket logging succeeded\n");
    } else {
        printf("put bucket logging failed, code:%d, error_code:%s, error_msg:%s, request_id:%s\n",
            resp_status->code, resp_status->error_code, resp_status->error_msg, resp_status->req_id); 
    }
    /* Release the memory pool. This releases the memory allocated to resources during the request. */
    aos_pool_destroy(pool);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # The China (Hangzhou) region is used as an example for the endpoint. Specify a region as needed.
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before running this code, set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

# Specify the bucket name, for example, examplebucket.
bucket = client.get_bucket('examplebucket')
# Set logging_bucket to the destination bucket for log files.
# Set my-log to the folder where log files are stored. If you specify this parameter, log files are saved in the specified folder. If you do not specify this parameter, log files are saved in the root directory of the destination bucket.
bucket.logging = Aliyun::OSS::BucketLogging.new(
  enable: true, target_bucket: 'logging_bucket', target_prefix: 'my-log')

API

Appelez l'opération PutBucketLogging pour activer la journalisation d'un compartiment.

Configurer la journalisation pour un compartiment vectoriel

Console

  1. Sur la page Compartiments vectoriels, cliquez sur le compartiment cible. Dans le volet de navigation de gauche, choisissez Gestion des journaux > Journalisation.

  2. Activez l'interrupteur Journalisation et configurez les paramètres suivants :

    • Emplacement de stockage cible : sélectionnez un compartiment pour stocker les fichiers de journaux. Le compartiment doit se trouver dans la même région que le compartiment vectoriel.

    • Préfixe de journal : définissez le répertoire et le préfixe des fichiers de journaux, par exemple MyLog-.

    • Rôle RAM : utilisez le rôle de service par défaut AliyunOSSLoggingDefaultRole pour la journalisation ou sélectionnez un rôle personnalisé.

Ossutil

Les exemples suivants montrent comment activer le stockage des journaux pour un compartiment nommé examplebucket. Le préfixe du fichier de journal est MyLog- et les journaux d'accès sont stockés dans le compartiment examplebucket.

  • Vous pouvez utiliser un fichier de configuration JSON. Le fichier bucket-logging-status.json contient le contenu suivant :

    {
      "LoggingEnabled": {
        "TargetBucket": "examplebucket",
        "TargetPrefix": "MyLog-"
      }
    }

    Exemple de commande :

    ossutil api put-bucket-logging --bucket examplebucket --bucket-logging-status file://bucket-logging-status.json
  • Vous pouvez utiliser des paramètres de configuration JSON. Exemple de commande :

    ossutil api put-bucket-logging --bucket examplebucket --bucket-logging-status "{\"LoggingEnabled\":{\"TargetBucket\":\"examplebucket\",\"TargetPrefix\":\"MyLog-\"}}"

SDK

Python

import argparse
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.vectors as oss_vectors

parser = argparse.ArgumentParser(description="vector put bucket logging sample")
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 endpoint to access OSS')
parser.add_argument('--account_id', help='The account ID.', required=True)
parser.add_argument('--target_bucket', help='The name of the target bucket.', required=True)

def main():
    args = parser.parse_args()

    # Load credentials from environment variables
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the SDK's default configuration
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region
    cfg.account_id = args.account_id
    cfg.use_internal_endpoint = True  # Set to False to use the public network endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    vector_client = oss_vectors.Client(cfg)

    result = vector_client.put_bucket_logging(oss_vectors.models.PutBucketLoggingRequest(
        bucket=args.bucket,
        bucket_logging_status=oss_vectors.models.BucketLoggingStatus(
            logging_enabled=oss_vectors.models.LoggingEnabled(
                target_bucket=args.target_bucket,
                target_prefix='log-prefix',
                logging_role='AliyunOSSLoggingDefaultRole'
            )
        )
    ))

    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
    )

if __name__ == "__main__":
    main()

Go

package main

import (
	"context"
	"flag"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/vectors"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

var (
	region     string
	bucketName string
	accountId  string
)

func init() {
	flag.StringVar(&region, "region", "", "The region in which the vector bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the vector bucket.")
	flag.StringVar(&accountId, "account-id", "", "The id of vector account.")
}

func main() {
	flag.Parse()
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	if len(accountId) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, accountId required")
	}

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region).WithAccountId(accountId).
		// To access OSS over the public internet, set this parameter to false or remove this line.
		WithUseInternalEndpoint(true)

	client := vectors.NewVectorsClient(cfg)

	request := &vectors.PutBucketLoggingRequest{
		Bucket: oss.Ptr(bucketName),
		BucketLoggingStatus: &vectors.BucketLoggingStatus{
			LoggingEnabled: &vectors.LoggingEnabled{
				TargetBucket: oss.Ptr("TargetBucket"),
				TargetPrefix: oss.Ptr("TargetPrefix"),
				LoggingRole:  oss.Ptr("AliyunOSSLoggingDefaultRole"),
			},
		},
	}
	result, err := client.PutBucketLogging(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put vector bucket logging %v", err)
	}

	log.Printf("put vector bucket logging result:%#v\n", result)
}

API

Appelez l'opération PutBucketLogging pour activer la journalisation d'un compartiment vectoriel.

Nommage des fichiers de journaux

Les fichiers de journaux utilisent la convention de nommage suivante :

<TargetPrefix><SourceBucket>YYYY-mm-DD-HH-MM-SS-UniqueString

Paramètre

Description

TargetPrefix

Le préfixe du nom du fichier de journal.

SourceBucket

Le compartiment source qui génère les journaux d'accès.

YYYY-mm-DD-HH-MM-SS

L'horodatage au format année, mois, jour, heure, minute et seconde. Les journaux utilisent une granularité horaire : HH=01 couvre 01:00:00 à 01:59:59. MM et SS sont toujours 00.

UniqueString

Un identifiant unique généré par le système pour le fichier de journal.

Format et exemple de journal

  • Format du journal

    Les journaux d'accès OSS contiennent des informations sur le demandeur et la ressource consultée. Le format est le suivant :

    RemoteIP Reserved Reserved Time "RequestURL" HTTPStatus SentBytes RequestTime "Referer" "UserAgent" "HostName" "RequestID" "LoggingFlag" "RequesterAliyunID" "Operation" "BucketName" "ObjectName" ObjectSize ServerCostTime "ErrorCode" RequestLength "UserID" DeltaDataSize "SyncRequest" "StorageClass" "TargetStorageClass" "TransmissionAccelerationAccessPoint" "AccessKeyID" "BucketARN"

    Champ

    Exemple

    Description

    RemoteIP

    192.168.0.1

    L'adresse IP du demandeur.

    Reserved

    -

    Un champ réservé. La valeur est toujours un tiret (-).

    Reserved

    -

    Un champ réservé. La valeur est toujours un tiret (-).

    Time

    03/Jan/2021:14:59:49 +0800

    L'heure à laquelle OSS a reçu la requête.

    RequestURL

    GET /example.jpg HTTP/1.0

    L'URL de la requête contenant une chaîne de requête.

    OSS ignore les paramètres de chaîne de requête commençant par x- mais les enregistre dans le journal d'accès. Utilisez les paramètres préfixés par x- pour baliser et localiser des requêtes spécifiques.

    HTTPStatus

    200

    Le code d'état HTTP renvoyé par OSS.

    SentBytes

    999131

    Le trafic descendant généré par la requête, en octets.

    RequestTime

    127

    Le temps d'achèvement de la requête, en millisecondes.

    Referer

    http://www.aliyun.com/product/oss

    Le référent HTTP de la requête.

    UserAgent

    curl/7.15.5

    L'en-tête User-Agent de la requête HTTP.

    HostName

    examplebucket.oss-cn-hangzhou.aliyuncs.com

    Le nom de domaine de destination.

    RequestID

    5FF16B65F05BC932307A3C3C

    L'ID de la requête.

    LoggingFlag

    true

    Indique si la journalisation est activée. Valeurs valides :

    • true : la journalisation est activée.

    • false : la journalisation n'est pas activée.

    RequesterAliyunID

    16571836914537****

    L'ID utilisateur du demandeur. Un tiret (-) indique une requête anonyme.

    Operation

    GetObject

    L'opération effectuée.

    BucketName

    examplebucket

    Le nom du compartiment de destination.

    ObjectName

    example.jpg

    Le nom de l'objet de destination.

    ObjectSize

    999131

    La taille de l'objet de destination, en octets.

    ServerCostTime

    88

    Le temps pris par OSS pour traiter la requête, en millisecondes.

    ErrorCode

    -

    Le code d'erreur renvoyé par OSS. Un tiret (-) indique qu'aucune erreur n'a été renvoyée.

    RequestLength

    302

    La longueur de la requête, en octets.

    UserID

    16571836914537****

    L'ID du propriétaire du compartiment.

    DeltaDataSize

    -

    La variation de la taille de l'objet. Un tiret (-) indique que la requête n'impliquait pas d'opération d'écriture.

    SyncRequest

    -

    Le type de requête. Valeurs valides :

    • - : une requête générale.

    • cdn : une requête d'origine CDN.

    • lifecycle : une requête de transition ou de suppression de données, déclenchée par une règle de cycle de vie.

    StorageClass

    Standard

    La classe de stockage de l'objet de destination. Valeurs valides :

    • Standard : Standard.

    • IA : Accès peu fréquent.

    • Archive : Archive.

    • Cold Archive : Cold Archive.

    • Deep Cold Archive : Deep Cold Archive.

    • - : la classe de stockage de l'objet n'a pas pu être obtenue.

    TargetStorageClass

    -

    La classe de stockage après une transition de cycle de vie ou CopyObject. Valeurs valides :

    • Standard : Changement vers Standard.

    • IA : Changement vers Accès peu fréquent.

    • Archive : Changement vers Archive.

    • Cold Archive : Changement vers Cold Archive.

    • Deep Cold Archive : Changement vers Deep Cold Archive.

    • - : aucune opération de conversion de classe de stockage d'objet n'est impliquée.

    TransmissionAccelerationAccessPoint

    -

    La région du point d'accès d'accélération de transfert utilisée pour accéder au compartiment. Exemple : cn-hangzhou pour la région Chine (Hangzhou).

    Un tiret (-) indique qu'aucun domaine d'accélération de transfert n'a été utilisé, ou que le point de terminaison se trouve dans la même région que le compartiment.

    AccessKeyID

    LTAI

    L'AccessKey ID du demandeur.

    • Pour les requêtes depuis la console, le champ de journal affiche un AccessKey ID temporaire commençant par TMP.

    • Pour les requêtes depuis un outil ou un SDK utilisant une clé à long terme, le champ de journal affiche un AccessKey ID commun. Exemple : LTAI.

    • Pour les requêtes utilisant des identifiants d'accès temporaires de Security Token Service (STS), le journal affiche un AccessKey ID temporaire commençant par STS.

    Remarque

    Un tiret (-) dans ce champ indique une requête anonyme.

    BucketARN

    acs:oss*

    Le descripteur de ressource globalement unique pour le compartiment.

  • Exemple de journal

    192.168.0.1 - - [03/Jan/2021:14:59:49 +0800] "GET /example.jpg HTTP/1.0" 200 999131 127 "http://www.aliyun.com/product/oss" "curl/7.15.5" "examplebucket.oss-cn-hangzhou.aliyuncs.com" "5FF16B65F05BC932307A3C3C" "true" "16571836914537****" "GetObject" "examplebucket" "example.jpg" 999131 88 "-" 302 "16571836914537****" - "cdn" "standard" "-" "-" "LTAI****************" "acs:oss***************"

    Importez les fichiers de journaux stockés dans Log Service pour analyse. Importer des données OSS. Vue d'ensemble des requêtes et analyses.

FAQ

Interrogation des requêtes interrompues

Les journaux d'accès OSS n'enregistrent pas les requêtes interrompues. Vérifiez la valeur de retour du SDK pour déterminer la cause de l'interruption.