更新时间:2023-11-09 GMT+08:00

开启桶日志

您可以通过setBucketLogging开启桶日志功能。

日志目标桶与源桶必须在同一个区域(region)。

已支持日志目标桶的存储类型:低频访问存储或归档存储或标准存储。

开启桶日志

以下代码展示了如何开启桶日志:

static OBSClient *client;
NSString *endPoint = @"your-endpoint";
// 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;本示例以ak和sk保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量AccessKeyID和SecretAccessKey。
// 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/intl/zh-cn/usermanual-ca/ca_01_0003.html
char* ak_env = getenv("AccessKeyID");
char* sk_env = getenv("SecretAccessKey");
NSString *AK = [NSString stringWithUTF8String:ak_env];
NSString *SK = [NSString stringWithUTF8String:sk_env];
    
// 初始化身份验证
OBSStaticCredentialProvider *credentialProvider = [[OBSStaticCredentialProvider alloc] initWithAccessKey:AK secretKey:SK];
    
//初始化服务配置
OBSServiceConfiguration *conf = [[OBSServiceConfiguration alloc] initWithURLString:endPoint credentialProvider:credentialProvider];
    
// 初始化client
client = [[OBSClient alloc] initWithConfiguration:conf];
    
//设置桶访问日志
// 第一步 设置目标桶的日志投递组访问权限
OBSUser *owner = [[OBSUser alloc] initWithID:@"ownerID"];
    
OBSACLGranteeLogDelivery *grantee = [OBSACLGranteeLogDelivery new];
OBSACLGrant *grant = [[OBSACLGrant alloc]initWithGrantee:grantee permission:OBSACLFull_Control];
    
// 设置目标桶的日志投递组为完全控制权限
OBSACLGranteeUser *userGrantee = [[OBSACLGranteeUser alloc]initWithID:@"granteeID"];
OBSACLGrant *userGrant = [[OBSACLGrant alloc]initWithGrantee:userGrantee permission:OBSACLFull_Control];
    
OBSACLGranteeAllUsers *alluserGrantee = [OBSACLGranteeAllUsers new];
OBSACLGrant *alluserGrant = [[OBSACLGrant alloc]initWithGrantee:alluserGrantee permission:OBSACLFull_Control];
    
OBSAccessControlPolicy *policy = [OBSAccessControlPolicy new];
policy.owner = owner;
[policy.accessControlList addObject:grant];
[policy.accessControlList addObject:userGrant];
    
OBSSetBucketACLWithPolicyRequest *setACLRequest = [[OBSSetBucketACLWithPolicyRequest alloc]initWithBucketName:@"bucketname" accessControlPolicy:policy];
    
[client setBucketACL:setACLRequest completionHandler:^(OBSSetBucketACLResponse *response, NSError *error){
    NSLog(@"%@",response);
}];
    
    
// 第二步 设置桶的日志管理配置
grant = [[OBSACLGrant alloc]initWithGrantee:grantee permission:OBSACLFull_Control];
    
OBSSetBucketLoggingRequest *request = [[OBSSetBucketLoggingRequest alloc]initWithBucketName:@"bucketname"];
    
OBSLoggingEnabled* enabledItem = [[OBSLoggingEnabled alloc]initWithTargetBucket:@"bucketname" targetPrefix:@"access-log"];
    
[enabledItem.targetGrantsList addObject:userGrant];
[enabledItem.targetGrantsList addObject:alluserGrant];
    
[request.loggingEnabledList addObject:enabledItem];
[client setBucketLogging:request completionHandler:^(OBSSetBucketLoggingResponse *response, NSError *error){
    NSLog(@"%@",response);
}];