Ative o registro de logs para gerar arquivos de log de acesso por hora e armazená-los em um bucket específico. Analise esses logs com o Log Service ou um cluster Spark.
Observações de uso
-
Se o bucket de origem tiver um atributo de região, o bucket de destino deverá pertencer à mesma conta e região. O bucket de destino pode ser igual ou diferente do bucket de origem.
Quando os buckets de origem e de destino são iguais, a operação de envio de logs gera logs adicionais, o que cria um loop. Use buckets de origem e de destino diferentes para evitar essa situação.
A geração dos arquivos de log pode levar até 48 horas. As requisições podem aparecer em arquivos de períodos adjacentes; portanto, não há garantia de que os logs de um período específico estejam completos ou disponíveis imediatamente.
-
O OSS gera um arquivo de log a cada hora até você desativar o registro. Exclua os arquivos de log desnecessários para reduzir custos de armazenamento.
Use Regras de ciclo de vida baseadas na última modificação para excluir periodicamente os arquivos de log.
Para evitar interrupção de serviço ou contaminação de dados ao configurar o envio de logs para um bucket com OSS-HDFS ativado, não defina o Log Prefix como
.dlsdata/.O OSS pode adicionar novos campos aos logs. Projete suas ferramentas de processamento de logs para lidar com essas adições. Por exemplo, o campo Bucket ARN será adicionado aos logs a partir de 17 de setembro de 2025.
Evite enviar logs para um bucket com ObjectWorm ativado. O ObjectWorm impede a exclusão de logs durante o período de retenção, o que causa aumento constante nos custos de armazenamento.
Configure registro de logs
Configure registro de logs para um bucket
Console
Acesse o console do OSS.
No painel de navegação à esquerda, clique em Buckets. Na página exibida, clique no nome do bucket de destino.
No painel de navegação à esquerda, escolha .
-
Na página Logging, ative a opção Logging e configure os parâmetros a seguir.
Parâmetro
Descrição
Target bucket
Bucket onde os logs serão armazenados. Padrão: o bucket atual. Selecione um bucket diferente na lista suspensa, se necessário. O bucket de destino deve pertencer à mesma conta e região.
Log prefix
Diretório no bucket de destino para os arquivos de log. Se não especificado, os logs vão para o diretório raiz. Exemplo: definir o prefixo como log/ armazena os logs no diretório log/.
RAM role
Função assumida pelo OSS para gravar logs.
Função de serviço padrão (Recomendado)
Cria automaticamente a função
AliyunOSSLoggingDefaultRolecom as permissões necessárias para todos os buckets da sua conta. Para usuários iniciantes: clique em Authorize Now para criar e autorizar a função.Função personalizada
Para limitar as permissões de registro de logs a um bucket específico, crie uma função personalizada:
Criar uma função RAM para um serviço confiável da Alibaba Cloud. Ao criar a função, defina Trusted Service como Cloud Service e Select Trusted Service como OSS.
Criar uma política personalizada usando o editor de scripts.
Criptografia 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/*" } ] }Sem criptografia KMS
Use esta política para buckets sem criptografia ou com criptografia do lado do servidor gerenciada pelo OSS.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": [ "oss:PutObject", "oss:AbortMultipartUpload" ], "Resource": "acs:oss:*:*:examplebucket/*" } ] }
Clique em Save.
Ossutil
Ative o registro de logs com a CLI ossutil. Instale ossutil.
O comando a seguir ativa o registro de logs para examplebucket, armazenando os logs de acesso em destBucket com o prefixo MyLog-.
ossutil api put-bucket-logging --bucket examplebucket --bucket-logging-status "{\"LoggingEnabled\":{\"TargetBucket\":\"destBucket\",\"TargetPrefix\":\"MyLog-\"}}"
Consulte put-bucket-logging.
SDK
Configure o registro de logs com os exemplos de SDK a seguir. Outros SDKs estão listados em SDKs.
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
Chame a operação PutBucketLogging para ativar o registro de logs em um bucket.
Configure registro de logs para um bucket vetorial
Console
Na página Vector Buckets, clique no bucket de destino. No painel de navegação à esquerda, escolha Log Management > Logging.
-
Ative a chave Logging e configure os seguintes parâmetros:
Target storage location: Selecione um bucket para armazenar os arquivos de log. O bucket deve estar na mesma região do bucket vetorial.
Log prefix: Defina o diretório e o prefixo para os arquivos de log, como
MyLog-.RAM role: Use a função de serviço padrão AliyunOSSLoggingDefaultRole para registro de logs ou selecione uma função personalizada.
Ossutil
Os exemplos a seguir mostram como ativar o armazenamento de logs para um bucket chamado examplebucket. O prefixo do arquivo de log é MyLog-, e os logs de acesso são armazenados no bucket examplebucket.
-
É possível usar um arquivo de configuração JSON. O arquivo bucket-logging-status.json contém o seguinte conteúdo:
{ "LoggingEnabled": { "TargetBucket": "examplebucket", "TargetPrefix": "MyLog-" } }Exemplo de comando:
ossutil api put-bucket-logging --bucket examplebucket --bucket-logging-status file://bucket-logging-status.json -
Também é possível usar parâmetros de configuração JSON. Exemplo de comando:
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(®ion, "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
Chame a operação PutBucketLogging para ativar o registro de logs em um bucket vetorial.
Nomenclatura de arquivos de log
Os arquivos de log seguem a convenção de nomenclatura abaixo:
<TargetPrefix><SourceBucket>YYYY-mm-DD-HH-MM-SS-UniqueString
|
Parâmetro |
Descrição |
|
TargetPrefix |
Prefixo do nome do arquivo de log. |
|
SourceBucket |
Bucket de origem que gera os logs de acesso. |
|
YYYY-mm-DD-HH-MM-SS |
Carimbo de data/hora no formato ano, mês, dia, hora, minuto e segundo. Os logs usam granularidade horária: HH=01 cobre de 01:00:00 a 01:59:59. MM e SS são sempre 00. |
|
UniqueString |
Identificador único gerado pelo sistema para o arquivo de log. |
Formato e exemplo de log
-
Formato do log
Os logs de acesso do OSS contêm informações sobre o solicitante e o recurso acessado. O formato é o seguinte:
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"Campo
Exemplo
Descrição
RemoteIP
192.168.0.1
Endereço IP do solicitante.
Reserved
-
Campo reservado. O valor é sempre um hífen (-).
Reserved
-
Campo reservado. O valor é sempre um hífen (-).
Time
03/Jan/2021:14:59:49 +0800
Momento em que o OSS recebeu a requisição.
RequestURL
GET /example.jpg HTTP/1.0
URL da requisição contendo a string de consulta.
O OSS ignora parâmetros de string de consulta que começam com
x-, mas os registra no log de acesso. Use parâmetros com prefixox-para marcar e localizar requisições específicas.HTTPStatus
200
Código de status HTTP retornado pelo OSS.
SentBytes
999131
Tráfego downstream gerado pela requisição, em bytes.
RequestTime
127
Tempo de conclusão da requisição, em milissegundos.
Referer
http://www.aliyun.com/product/oss
HTTP Referer da requisição.
UserAgent
curl/7.15.5
Cabeçalho User-Agent da requisição HTTP.
HostName
examplebucket.oss-cn-hangzhou.aliyuncs.com
Nome de domínio de destino.
RequestID
5FF16B65F05BC932307A3C3C
ID da requisição.
LoggingFlag
true
Indica se o registro de logs está ativado. Valores válidos:
true: Registro de logs ativado.
false: Registro de logs não ativado.
RequesterAliyunID
16571836914537****
ID de usuário do solicitante. Um hífen (-) indica uma requisição anônima.
Operation
GetObject
Operação executada.
BucketName
examplebucket
Nome do bucket de destino.
ObjectName
example.jpg
Nome do objeto de destino.
ObjectSize
999131
Tamanho do objeto de destino, em bytes.
ServerCostTime
88
Tempo que o OSS levou para processar a requisição, em milissegundos.
ErrorCode
-
Código de erro retornado pelo OSS. Um hífen (-) indica que nenhum erro foi retornado.
RequestLength
302
Comprimento da requisição, em bytes.
UserID
16571836914537****
ID do proprietário do bucket.
DeltaDataSize
-
Alteração no tamanho do objeto. Um hífen (-) indica que a requisição não envolveu uma operação de gravação.
SyncRequest
-
Tipo de requisição. Valores válidos:
-: Requisição geral.
cdn: Requisição de origem CDN.
lifecycle: Requisição para transição ou exclusão de dados, acionada por uma regra de ciclo de vida.
StorageClass
Standard
Classe de armazenamento do objeto de destino. Valores válidos:
Standard: Standard.
IA: Infrequent Access.
Archive: Archive.
Cold Archive: Cold Archive.
Deep Cold Archive: Deep Cold Archive.
-: Não foi possível obter a classe de armazenamento do objeto.
TargetStorageClass
-
Classe de armazenamento após uma transição de ciclo de vida ou CopyObject. Valores válidos:
Standard: Alterado para Standard.
IA: Alterado para Infrequent Access.
Archive: Alterado para Archive.
Cold Archive: Alterado para Cold Archive.
Deep Cold Archive: Alterado para Deep Cold Archive.
-: Nenhuma operação de conversão de classe de armazenamento de objeto envolvida.
TransmissionAccelerationAccessPoint
-
Região do endpoint de aceleração de transferência usada para acessar o bucket. Exemplo: cn-hangzhou para a região China (Hangzhou).
Um hífen (-) indica que nenhum domínio de aceleração de transferência foi usado ou que o endpoint está na mesma região do bucket.
AccessKeyID
LTAI
AccessKey ID do solicitante.
Para requisições do console, o campo de log mostra um AccessKey ID temporário que começa com TMP.
Para requisições de uma ferramenta ou SDK usando uma chave de longo prazo, o campo de log mostra um AccessKey ID comum. Exemplo:
LTAI.Para requisições usando credenciais de acesso temporárias do Security Token Service (STS), o log mostra um AccessKey ID temporário que começa com STS.
NotaUm hífen (-) neste campo indica uma requisição anônima.
BucketARN
acs:oss*
Descritor de recurso globalmente exclusivo para o bucket.
-
Exemplo de log
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***************"Importe os arquivos de log armazenados no Log Service para análise. Consulte Importar dados do OSS e Visão geral de consulta e análise.