### Swift Configuration and Client Creation Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Demonstrates how to import the SDK, create a LogProducerConfig object with necessary credentials and endpoint details, configure various producer settings, and initialize a LogProducerClient. ```APIDOC ## Swift Configuration and Client Creation ### Description This section details the steps to configure the Aliyun Log producer in Swift, including setting up the configuration object with endpoint, project, logstore, and access credentials, as well as customizing producer behavior like topic, tags, packet size, timeout, buffer limits, and persistent transfer settings. It also shows how to create a `LogProducerClient` with a callback function for send completion. ### Import ```swift import AliyunLogProducer ``` ### Create Config ```swift // endpoint前需要加 https:// let endpoint = "project's_endpoint" let project = "project_name" let logstore = "logstore_name" let accesskeyid = "your_accesskey_id" let accesskeysecret = "your_accesskey_secret" let config = LogProducerConfig(endpoint:endpoint, project:project, logstore:logstore, accessKeyID:accesskeyid, accessKeySecret:accesskeysecret)! // 指定sts token 创建config,过期之前调用ResetSecurityToken重置token // let config = LogProducerConfig(endpoint:endpoint, project:project, logstore:logstore, accessKeyID:accesskeyid, accessKeySecret:accesskeysecret, securityToken:securityToken) ``` ### Configure Config & Create Client ```swift // 设置主题 config.setTopic("test_topic") // 设置tag信息,此tag会附加在每条日志上 config.addTag("test", value:"test_tag") // 每个缓存的日志包的大小上限,取值为1~5242880,单位为字节。默认为1024 * 1024 config.setPacketLogBytes(1024*1024) // 每个缓存的日志包中包含日志数量的最大值,取值为1~4096,默认为1024 config.setPacketLogCount(1024) // 被缓存日志的发送超时时间,如果缓存超时,则会被立即发送,单位为毫秒,默认为3000 config.setPacketTimeout(3000) // 单个Producer Client实例可以使用的内存的上限,超出缓存时add_log接口会立即返回失败 // 默认为64 * 1024 * 1024 config.setMaxBufferLimit(64*1024*1024) // 发送线程数,默认为1,不建议修改此配置 // 开启断点续传功能后,sendThreadCount强制为1 config.setSendThreadCount(1) // 1 开启断点续传功能, 0 关闭 // 每次发送前会把日志保存到本地的binlog文件,只有发送成功才会删除,保证日志上传At Least Once config.setPersistent(1) // 持久化的文件名,需要保证文件所在的文件夹已创建。 let file = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first let path = file! + "/log.dat" config.setPersistentFilePath(path) // 是否每次AddLog强制刷新,高可靠性场景建议打开 config.setPersistentForceFlush(1) // 持久化文件滚动个数,建议设置成10。 config.setPersistentMaxFileCount(10) // 每个持久化文件的大小,建议设置成1-10M config.setPersistentMaxFileSize(1024*1024) // 本地最多缓存的日志数,不建议超过1M,通常设置为65536即可 config.setPersistentMaxLogCount(65536) config.setGetTimeUnixFunc({ let time = Date().timeIntervalSince1970 return UInt32(time); }) let callbackFunc: on_log_producer_send_done_function = {config_name,result,log_bytes,compressed_bytes,req_id,error_message,raw_buffer,user_param in let res = LogProducerResult(rawValue: Int(result)) // print(res!) // let req = String(cString: req_id!) // print(req) // print(log_bytes) // print(compressed_bytes) } var client = LogProducerClient(logProducerConfig:config, callback:callbackFunc) // client = LogProducerClient(logProducerConfig:config) ``` ``` -------------------------------- ### Manage Credentials with SLSCredentials Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Configures basic credentials using AccessKey or STS Token and demonstrates creating module-specific credentials for network diagnosis and tracing. Includes setting up dynamic STS Token refresh callbacks. ```objc #import // 创建基础凭证 SLSCredentials *credentials = [SLSCredentials credentials]; credentials.instanceId = @"your-instance-id"; credentials.endpoint = @"https://cn-hangzhou.log.aliyuncs.com"; credentials.project = @"my-project"; credentials.accessKeyId = @"YOUR_AK_ID"; credentials.accessKeySecret = @"YOUR_AK_SECRET"; // STS 临时凭证(可选) credentials.securityToken = @"your-sts-token"; // 为网络诊断模块创建独立凭证 SLSNetworkDiagnosisCredentials *ndCreds = [credentials createNetworkDiagnosisCredentials]; ndCreds.logstore = @"nd-logstore"; ndCreds.secretKey = @"nd-secret-key"; // 网络诊断专用密钥 ndCreds.siteId = @"site-001"; [ndCreds putExtension:@"cn-hangzhou" forKey:@"region"]; // 为链路追踪模块创建独立凭证 SLSTraceCredentials *traceCreds = [credentials createTraceCredentials]; traceCreds.logstore = @"trace-logstore"; // 为 Trace 下的 Logs 信号创建独立 logstore SLSLogsCredentials *logsCreds = [traceCreds createLogsCredentials]; logsCreds.logstore = @"logs-logstore"; // STS Token 过期后动态刷新(无需重启 SDK) // 在 STS Token 即将过期时注册回调更新凭证 [[SLSCocoa sharedInstance] registerCredentialsCallback:^(NSString *feature, NSString *result) { // feature: 触发刷新的功能模块名称 // 拉取新 Token 后刷新 SLSCredentials *newCreds = [SLSCredentials credentials]; newCreds.accessKeyId = @"NEW_STS_KEY_ID"; newCreds.accessKeySecret = @"NEW_STS_KEY_SECRET"; newCreds.securityToken = @"NEW_STS_TOKEN"; [[SLSCocoa sharedInstance] setCredentials:newCreds]; }]; ``` -------------------------------- ### Initialize LogProducerConfig with AccessKey Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Configure the log upload destination, project, logstore, and authentication using AccessKey. For production, STS Token is recommended. ```swift let config = LogProducerConfig( endpoint: "https://cn-hangzhou.log.aliyuncs.com", project: "my-project", logstore: "my-logstore", accessKeyID: "YOUR_ACCESS_KEY_ID", accessKeySecret: "YOUR_ACCESS_KEY_SECRET" )! ``` -------------------------------- ### Create and Manage Spans with SLSTracer Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Demonstrates creating spans using SpanBuilder, automatic span management with blocks, and quick span creation. Includes logging events, recording exceptions, and configuring automatic URLSession instrumentation. ```objc #import #import // 方式一:使用 SpanBuilder 精细控制 SLSSpan *span = [[SLSTracer spanBuilder:@"checkout"] setKind:SLSCLIENT] addAttributes:@[ [SLSAttribute of:@"user.id" stringValue:@"user-123"], [SLSAttribute of:@"order.amount" doubleValue:99.9], [SLSAttribute of:@"order.items" intValue:3] ]] build]; // 设置父 Span(手动传播上下文) // [spanBuilder setParent:parentSpan]; // 添加事件节点 [span addEvent:@"payment_started"]; [span addEvent:@"payment_completed" attributes:@[ [SLSAttribute of:@"payment.method" stringValue:@"Alipay"] ]]; // 记录异常 @try { // 业务逻辑 } @catch (NSException *e) { [span recordException:e attributes:@[ [SLSAttribute of:@"retry.count" intValue:1] ]]; span.statusCode = ERROR; span.statusMessage = e.reason; } [span end]; // 必须调用 end,否则数据不会上报 // 方式二:Block 作用域(自动 end) [SLSTracer withinSpan:@"database_query" active:YES block:^{ // Block 内的代码被自动包裹在一个 Span 中 // 执行完毕后 Span 自动结束 [self fetchUserFromDB:@"user-123"]; }]; // 方式三:快速创建并激活为当前 Span SLSSpan *activeSpan = [SLSTracer startSpan:@"api_call" active:YES]; // ... 业务逻辑 ... [activeSpan end]; // 上报日志(Logs 信号,与 Trace 关联) [SLSTracer log:@"订单创建成功" :SLSLogsLevelInfo]; // NSURLSession 自动插桩委托(过滤特定请求) [SLSTracer registerURLSessionInstrumentationDelegate:self]; // 实现协议: // - (BOOL)shouldInstrument:(NSURLRequest *)request { // return [request.URL.host hasSuffix:@"aliyuncs.com"]; // } ``` -------------------------------- ### LogProducerConfig Initialization and Configuration Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Demonstrates how to initialize and configure LogProducerConfig for setting up log uploading destinations, performance parameters, and persistence options. ```APIDOC ## LogProducerConfig — 日志生产者配置 `LogProducerConfig` 用于配置日志上传的目标 endpoint、Project、Logstore 以及各类性能参数,是创建 `LogProducerClient` 的前置步骤。 ```swift import AliyunLogProducer // 使用 AccessKey 初始化(生产环境建议使用 STS Token) let config = LogProducerConfig( endpoint: "https://cn-hangzhou.log.aliyuncs.com", project: "my-project", logstore: "my-logstore", accessKeyID: "YOUR_ACCESS_KEY_ID", accessKeySecret: "YOUR_ACCESS_KEY_SECRET" )! // 使用 STS Token 初始化(临时凭证,过期前需调用 ResetSecurityToken) // let config = LogProducerConfig( // endpoint: "https://cn-hangzhou.log.aliyuncs.com", // project: "my-project", // logstore: "my-logstore", // accessKeyID: stsKeyId, // accessKeySecret: stsKeySecret, // securityToken: stsToken // )! // 设置日志主题和自定义 Tag(附加在每条日志上) config.setTopic("ios-app-topic") config.addTag("app_version", value: "1.0.0") config.addTag("env", value: "production") // 聚合策略:单包最大字节数 / 最大条数 / 发送超时(毫秒) config.setPacketLogBytes(1024 * 1024) // 1MB config.setPacketLogCount(1024) config.setPacketTimeout(3000) // 3 秒 // 内存缓冲上限(超出后 AddLog 立即返回失败) config.setMaxBufferLimit(64 * 1024 * 1024) // 64MB // 断点续传:日志先写本地 binlog,发送成功后删除,保证 At-Least-Once config.setPersistent(1) let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! config.setPersistentFilePath(docDir + "/sls_log.dat") config.setPersistentForceFlush(1) // 每次 AddLog 都强制 fsync(高可靠场景) config.setPersistentMaxFileCount(10) // 最多滚动 10 个文件 config.setPersistentMaxFileSize(1024 * 1024) // 每个文件最大 1MB config.setPersistentMaxLogCount(65536) // 本地最多缓存 65536 条 // 压缩类型:0=不压缩,1=LZ4(默认) config.setCompressType(1) // 可选:NTP 时间偏移修正(设备时间不准时使用) // config.setNtpTimeOffset(100) // 可选:STS Token 过期后重置(无需重建 client) // config.resetSecurityToken("newKeyId", accessKeySecret: "newSecret", securityToken: "newToken") ``` ``` -------------------------------- ### Objective-C Configuration Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Provides instructions for configuring the Aliyun Log producer in Objective-C, including importing the framework and initializing the LogProducerConfig with essential parameters. ```APIDOC ## Objective-C Configuration ### Description This section outlines the configuration process for the Aliyun Log producer using Objective-C. It covers importing the necessary header file and initializing the `LogProducerConfig` object with endpoint, project, logstore, and access key credentials. ### Import ```objectivec #import "AliyunLogProducer/AliyunLogProducer.h" ``` ### Create Config ```objectivec // endpoint前需要加 https:// NSString* endpoint = @"project's_endpoint"; NSString* project = @"project_name"; NSString* logstore = @"logstore_name"; NSString* accesskeyid = @"your_accesskey_id"; NSString* accesskeysecret = @"your_accesskey_secret"; LogProducerConfig* config = [[LogProducerConfig alloc] initWithEndpoint:endpoint project:project logstore:logstore accessKeyID:accesskeyid accessKeySecret:accesskeysecret]; // 指定sts token 创建config,过期之前调用ResetSecurityToken重置token // LogProducerConfig* config = [[LogProducerConfig alloc] initWithEndpoint:endpoint project:project logstore:logstore accessKeyID:accesskeyid accessKeySecret:accesskeysecret securityToken:securityToken]; ``` ``` -------------------------------- ### Create LogProducerClient with Callback Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Instantiate the LogProducerClient with a configuration and a callback function to handle send results. The callback provides details on success or failure. ```swift let callback: on_log_producer_send_done_function = { configName, result, logBytes, compressedBytes, reqId, errorMessage, rawBuffer, userParam in let res = LogProducerResult(rawValue: Int(result)) switch res { case .some(.logProducerOK): print("发送成功,压缩前 \(logBytes) 字节,压缩后 \(compressedBytes) 字节") case .some(.logProducerSendNetworkError): print("网络错误,requestId: \(String(cString: reqId!))") case .some(.logProducerSendUnauthorized): print("鉴权失败,请检查 AccessKey 或刷新 STS Token") default: print("发送结果: \(String(describing: res))") } } client = LogProducerClient(logProducerConfig: config, callback: callback) ``` -------------------------------- ### Initialize and Use SLSNetworkDiagnosis Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Initializes the SLSNetworkDiagnosis SDK and demonstrates various network diagnostic tests like HTTP, Ping, TCP Ping, MTR, and DNS. Includes optional global callback registration and dynamic extension field updates. ```objc #import SLSNetworkDiagnosis *nd = [SLSNetworkDiagnosis sharedInstance]; // 注册统一结果回调(可选,也可在每次诊断时单独传入) [nd registerCallback2:^(SLSResponse *response) { NSLog(@"诊断类型: %@", response.type); NSLog(@"诊断结果: %@", response.content); if (response.error) { NSLog(@"错误信息: %@", response.error); } }]; // HTTP 探测 SLSHttpRequest *httpReq = [[SLSHttpRequest alloc] init]; httpReq.domain = @"www.aliyun.com"; httpReq.maxTimes = 3; httpReq.timeout = 10; httpReq.headerOnly = NO; [nd http2:httpReq callback:^(SLSResponse *response) { NSLog(@"HTTP 探测结果: %@", response.content); }]; // ICMP Ping SLSPingRequest *pingReq = [[SLSPingRequest alloc] init]; pingReq.domain = @"8.8.8.8"; pingReq.maxTimes = 5; pingReq.timeout = 3; pingReq.size = 64; [nd ping2:pingReq]; // TCP Ping(检测端口连通性) SLSTcpPingRequest *tcpReq = [[SLSTcpPingRequest alloc] init]; tcpReq.domain = @"www.aliyun.com"; tcpReq.port = 443; tcpReq.maxTimes = 3; [nd tcpPing2:tcpReq]; // MTR 路由追踪 SLSMtrRequest *mtrReq = [[SLSMtrRequest alloc] init]; mtrReq.domain = @"www.aliyun.com"; mtrReq.maxTTL = 30; mtrReq.maxPaths = 1; mtrReq.protocol = SLS_MTR_PROROCOL_ICMP; [nd mtr2:mtrReq]; // DNS 解析 SLSDnsRequest *dnsReq = [[SLSDnsRequest alloc] init]; dnsReq.domain = @"www.aliyun.com"; dnsReq.nameServer = @"8.8.8.8"; dnsReq.type = @"A"; [nd dns2:dnsReq callback:^(SLSResponse *response) { NSLog(@"DNS 解析结果: %@", response.content); }]; // 动态更新扩展字段(附加到后续所有诊断结果) [nd updateExtensions:@{@"page": @"HomeViewController", @"network": @"WiFi"}]; ``` -------------------------------- ### Configure LogProducerConfig Topic and Tags Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Set a topic for logs and add custom tags like application version and environment to each log entry. ```swift config.setTopic("ios-app-topic") config.addTag("app_version", value: "1.0.0") config.addTag("env", value: "production") ``` -------------------------------- ### Import AliyunLogProducer in Swift Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Import the AliyunLogProducer framework to use its functionalities in your Swift code. ```swift import AliyunLogProducer ``` -------------------------------- ### Swift Write Data Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Shows how to create a Log object, add content to it, and send it using the LogProducerClient. It also explains the `flush` parameter for immediate sending. ```APIDOC ## Swift Write Data ### Description This section demonstrates how to create a log entry, add key-value content to it, and send it using the `LogProducerClient`. It also explains the `flush` parameter which controls whether the log should be sent immediately. ### Write Data ```swift let log = Log() let logTime = Date().timeIntervalSince1970 //不设置默认当前时间 log.setTime(useconds_t(logTime)) log.putContent("k1", value:"v1") log.putContent("k2", value:"v2") // addLog第二个参数flush,是否立即发送,1代表立即发送,不设置时默认为0 let res = client?.add(log, flush:0) ``` ``` -------------------------------- ### Initialize LogProducerConfig with STS Token Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Configure log upload parameters using STS Token. Remember to call ResetSecurityToken before the token expires. ```swift let config = LogProducerConfig( endpoint: "https://cn-hangzhou.log.aliyuncs.com", project: "my-project", logstore: "my-logstore", accessKeyID: stsKeyId, accessKeySecret: stsKeySecret, securityToken: stsToken )! ``` -------------------------------- ### CocoaPods Integration for Aliyun Log iOS SDK Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Add the Aliyun Log SDK modules to your Podfile as needed. Core producer is required, while crash reporter, network diagnosis, and OpenTelemetry are optional. ```ruby pod 'AliyunLogProducer', '~> 4.3.3' pod 'AliyunLogCrashReporter', '~> 4.3.3' pod 'AliyunLogNetworkDiagnosis', '~> 4.3.3' pod 'AliyunLogOTelCommon', '~> 4.3.3' pod 'AliyunLogOtlpExporter', '~> 4.3.3' ``` -------------------------------- ### Configure Producer Client Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Set up the LogProducerConfig object with various parameters to control logging behavior, such as topic, tags, packet size, buffer limits, and persistent storage options. Ensure the persistent file path is valid and directories are created if persistent storage is enabled. ```objective-c // 设置主题 [config SetTopic:@"test_topic"]; // 设置tag信息,此tag会附加在每条日志上 [config AddTag:@"test" value:@"test_tag"]; // 每个缓存的日志包的大小上限,取值为1~5242880,单位为字节。默认为1024 * 1024 [config SetPacketLogBytes:1024*1024]; // 每个缓存的日志包中包含日志数量的最大值,取值为1~4096,默认为1024 [config SetPacketLogCount:1024]; // 被缓存日志的发送超时时间,如果缓存超时,则会被立即发送,单位为毫秒,默认为3000 [config SetPacketTimeout:3000]; // 单个Producer Client实例可以使用的内存的上限,超出缓存时add_log接口会立即返回失败 // 默认为64 * 1024 * 1024 [config SetMaxBufferLimit:64*1024*1024]; // 发送线程数,默认为1,不建议修改此配置 // 开启断点续传功能后,sendThreadCount强制为1 [config SetSendThreadCount:1]; // 1 开启断点续传功能, 0 关闭 // 每次发送前会把日志保存到本地的binlog文件,只有发送成功才会删除,保证日志上传At Least Once [config SetPersistent:1]; // 持久化的文件名,需要保证文件所在的文件夹已创建。 [config SetPersistentFilePath:Path]; // 是否每次AddLog强制刷新,高可靠性场景建议打开 [config SetPersistentForceFlush:1]; // 持久化文件滚动个数,建议设置成10。 [config SetPersistentMaxFileCount:10]; // 每个持久化文件的大小,建议设置成1-10M [config SetPersistentMaxFileSize:1024*1024]; // 本地最多缓存的日志数,不建议超过1M,通常设置为65536即可 [config SetPersistentMaxLogCount:65536]; // 注册 获取服务器时间 的函数 [config SetGetTimeUnixFunc:time]; //创建client client = [[LogProducerClient alloc] initWithLogProducerConfig:config]; ``` -------------------------------- ### Swift Package Manager Integration for Aliyun Log iOS SDK Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Specify the Aliyun Log SDK package in your Package.swift file and list the desired products as dependencies for your target. ```swift dependencies: [ .package(url: "https://github.com/aliyun/aliyun-log-ios-sdk.git", from: "4.3.3") ], targets: [ .target( name: "MyApp", dependencies: [ .product(name: "AliyunLogProducer", package: "aliyun-log-ios-sdk"), .product(name: "AliyunLogCrashReporter", package: "aliyun-log-ios-sdk"), ] ) ] ``` -------------------------------- ### Create LogProducerConfig in Objective-C Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Initialize a LogProducerConfig object with endpoint, project, logstore, and access key credentials. STS token can also be provided for temporary authentication. ```objectivec // endpoint前需要加 https:// NSString* endpoint = @"project's_endpoint"; NSString* project = @"project_name"; NSString* logstore = @"logstore_name"; NSString* accesskeyid = @"your_accesskey_id"; NSString* accesskeysecret = @"your_accesskey_secret"; LogProducerConfig* config = [[LogProducerConfig alloc] initWithEndpoint:endpoint project:project logstore:logstore accessKeyID:accesskeyid accessKeySecret:accesskeysecret]; ``` ```objectivec // 指定sts token 创建config,过期之前调用ResetSecurityToken重置token // LogProducerConfig* config = [[LogProducerConfig alloc] initWithEndpoint:endpoint project:project logstore:logstore accessKeyID:accesskeyid accessKeySecret:accesskeysecret securityToken:securityToken]; ``` -------------------------------- ### LogProducerClient Usage for Sending Logs Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Illustrates how to create a LogProducerClient using the configured LogProducerConfig and send log entries with a callback for handling send results. ```APIDOC ## LogProducerClient — 日志写入客户端 `LogProducerClient` 是日志写入的核心接口,基于 `LogProducerConfig` 创建,负责将 `Log` 对象异步上传至 SLS,并通过回调返回发送结果。 ```swift import AliyunLogProducer var client: LogProducerClient? // 创建带回调的 client(推荐) let callback: on_log_producer_send_done_function = { configName, result, logBytes, compressedBytes, reqId, errorMessage, rawBuffer, userParam in let res = LogProducerResult(rawValue: Int(result)) switch res { case .some(.logProducerOK): print("发送成功,压缩前 \(logBytes) 字节,压缩后 \(compressedBytes) 字节") case .some(.logProducerSendNetworkError): print("网络错误,requestId: \(String(cString: reqId!))") case .some(.logProducerSendUnauthorized): print("鉴权失败,请检查 AccessKey 或刷新 STS Token") default: print("发送结果: \(String(describing: res))") } } client = LogProducerClient(logProducerConfig: config, callback: callback) // 写入日志 let log = Log() log.putContent("level", value: "INFO") log.putContent("message", value: "用户登录成功") log.putContent("user_id", intValue: 12345) log.putContent("latency_ms", doubleValue: 38.5) log.putContent("success", boolValue: true) // 写入 JSON 对象 _ = log.putContent("metadata", dictValue: ["platform": "iOS", "os_version": "17.0"]) // flush=0 异步发送(推荐);flush=1 立即触发发送 let result = client?.add(log, flush: 0) // 销毁(退出前调用,等待缓冲区发送完毕) // client?.destroyLogProducer() ``` ``` -------------------------------- ### Import AliyunLogProducer in Objective-C Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Import the AliyunLogProducer header file to use its functionalities in your Objective-C code. ```objectivec #import "AliyunLogProducer/AliyunLogProducer.h" ``` -------------------------------- ### Add AliyunLogProducer to Podfile Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Specify the AliyunLogProducer dependency in your project's Podfile. ```ruby pod 'AliyunLogProducer', '~> 2.2.25' ``` -------------------------------- ### Create Log Object and Add Content Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Create a Log object and populate it with key-value pairs. Supports string, integer, double, boolean, and dictionary values. ```swift let log = Log() log.putContent("level", value: "INFO") log.putContent("message", value: "用户登录成功") log.putContent("user_id", intValue: 12345) log.putContent("latency_ms", doubleValue: 38.5) log.putContent("success", boolValue: true) // 写入 JSON 对象 _ = log.putContent("metadata", dictValue: ["platform": "iOS", "os_version": "17.0"]) ``` -------------------------------- ### Create LogProducerConfig in Swift Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Initialize a LogProducerConfig object with endpoint, project, logstore, and access key credentials. STS token can also be provided for temporary authentication. ```swift // endpoint前需要加 https:// let endpoint = "project's_endpoint"; let project = "project_name"; let logstore = "logstore_name"; let accesskeyid = "your_accesskey_id"; let accesskeysecret = "your_accesskey_secret"; let config = LogProducerConfig(endpoint:endpoint, project:project, logstore:logstore, accessKeyID:accesskeyid, accessKeySecret:accesskeysecret)! ``` ```swift // 指定sts token 创建config,过期之前调用ResetSecurityToken重置token // let config = LogProducerConfig(endpoint:endpoint, project:project, logstore:logstore, accessKeyID:accesskeyid, accessKeySecret:accesskeysecret, securityToken:securityToken) ``` -------------------------------- ### Write Log Data in Swift Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Create a Log object, set its timestamp and content, and add it to the client. The `flush` parameter determines if the log should be sent immediately. ```swift let log = Log() let logTime = Date().timeIntervalSince1970 //不设置默认当前时间 log.setTime(useconds_t(logTime)) log.putContent("k1", value:"v1") log.putContent("k2", value:"v2") // addLog第二个参数flush,是否立即发送,1代表立即发送,不设置时默认为0 let res = client?.add(log, flush:0) ``` -------------------------------- ### Write Log Data Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Create a Log object, set its timestamp (optional, defaults to current time), add key-value content, and send it using the LogProducerClient. The `flush` parameter determines if the log is sent immediately. ```objective-c Log* log = [[Log alloc] init]; int logTime = [[NSDate date] timeIntervalSince1970]; //不设置默认当前时间 [log SetTime:logTime]; [log PutContent:@"k1" value:@"v1"]; [log PutContent:@"k2" value:@"v2"]; // addLog第二个参数flush,是否立即发送,1代表立即发送,不设置时默认为0 LogProducerResult res = [client AddLog:log flush:0]; ``` -------------------------------- ### Configure LogProducerConfig Aggregation Settings Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Adjust packet size, log count, and timeout for log aggregation. These parameters control how logs are bundled before sending. ```swift config.setPacketLogBytes(1024 * 1024) // 1MB config.setPacketLogCount(1024) config.setPacketTimeout(3000) // 3 秒 ``` -------------------------------- ### Configure LogProducerConfig for Persistent Storage Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Enable persistent storage for logs to ensure at-least-once delivery. Configure file path, rotation, and size limits. ```swift config.setPersistent(1) let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! config.setPersistentFilePath(docDir + "/sls_log.dat") config.setPersistentForceFlush(1) // 每次 AddLog 都强制 fsync(高可靠场景) config.setPersistentMaxFileCount(10) // 最多滚动 10 个文件 config.setPersistentMaxFileSize(1024 * 1024) // 每个文件最大 1MB config.setPersistentMaxLogCount(65536) // 本地最多缓存 65536 条 ``` -------------------------------- ### Configure Advanced LogProducer Parameters Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Configure advanced parameters for LogProducerConfig, including network timeouts, time offset correction, and delayed log processing strategies, suitable for complex network environments and offline scenarios. Debug logging is available for development and debugging purposes. ```objc #import LogProducerConfig *config = [[LogProducerConfig alloc] initWithEndpoint:@"https://cn-hangzhou.log.aliyuncs.com" project:@"my-project" logstore:@"my-logstore" accessKeyID:@"YOUR_AK_ID" accessKeySecret:@"YOUR_AK_SECRET"]; // 网络超时参数 [config SetConnectTimeoutSec:10]; // 连接超时 10 秒 [config SetSendTimeoutSec:15]; // 发送超时 15 秒 // 线程销毁等待时间(退出时等待 flush) [config SetDestroyFlusherWaitSec:2]; [config SetDestroySenderWaitSec:2]; // 压缩:0=不压缩,1=LZ4(默认) [config SetCompressType:1]; // 设备时间不准时的 NTP 偏移修正(单位:秒) // 示例:设备时间比标准时间慢 100 秒 [config SetNtpTimeOffset:100]; // 离线日志处理策略(断点续传场景,设备离线数天后重新上线) [config SetMaxLogDelayTime:7 * 24 * 3600]; // 超过 7 天的日志触发处理 [config SetDropDelayLog:1]; // 1=丢弃超时日志,0=修改为当前时间 // 鉴权失败日志处理:0=不丢弃(默认),1=丢弃 [config SetDropUnauthorizedLog:0]; // 注入自定义 HTTP 请求头(如用于内网鉴权) [config setHttpHeaderInjector:^NSArray *(NSArray *srcHeaders) { NSMutableArray *headers = [srcHeaders mutableCopy]; [headers addObject:@"X-Custom-Token"]; [headers addObject:@"my-custom-token-value"]; return headers; }]; // 开启 Debug 日志(仅开发调试时使用) [LogProducerConfig Debug]; // 验证配置有效性 NSAssert([config IsValid], @"LogProducerConfig 配置无效,请检查 endpoint/project/logstore"); ``` -------------------------------- ### Configure LogProducerConfig Memory Buffer Limit Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Set the maximum memory buffer size. If exceeded, AddLog calls will fail immediately. ```swift config.setMaxBufferLimit(64 * 1024 * 1024) // 64MB ``` -------------------------------- ### Configure LogProducerConfig in Swift Source: https://github.com/aliyun/aliyun-log-ios-sdk/blob/master/README.md Set various configuration options for the LogProducerConfig, including topic, tags, packet size, timeout, buffer limits, and persistent upload settings. ```swift // 设置主题 config.setTopic("test_topic") // 设置tag信息,此tag会附加在每条日志上 config.addTag("test", value:"test_tag") // 每个缓存的日志包的大小上限,取值为1~5242880,单位为字节。默认为1024 * 1024 config.setPacketLogBytes(1024*1024) // 每个缓存的日志包中包含日志数量的最大值,取值为1~4096,默认为1024 config.setPacketLogCount(1024) // 被缓存日志的发送超时时间,如果缓存超时,则会被立即发送,单位为毫秒,默认为3000 config.setPacketTimeout(3000) // 单个Producer Client实例可以使用的内存的上限,超出缓存时add_log接口会立即返回失败 // 默认为64 * 1024 * 1024 config.setMaxBufferLimit(64*1024*1024) // 发送线程数,默认为1,不建议修改此配置 // 开启断点续传功能后,sendThreadCount强制为1 config.setSendThreadCount(1) // 1 开启断点续传功能, 0 关闭 // 每次发送前会把日志保存到本地的binlog文件,只有发送成功才会删除,保证日志上传At Least Once config.setPersistent(1) // 持久化的文件名,需要保证文件所在的文件夹已创建。 let file = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first let path = file! + "/log.dat" config.setPersistentFilePath(path) // 是否每次AddLog强制刷新,高可靠性场景建议打开 config.setPersistentForceFlush(1) // 持久化文件滚动个数,建议设置成10。 config.setPersistentMaxFileCount(10) // 每个持久化文件的大小,建议设置成1-10M config.setPersistentMaxFileSize(1024*1024) // 本地最多缓存的日志数,不建议超过1M,通常设置为65536即可 config.setPersistentMaxLogCount(65536) config.setGetTimeUnixFunc({ let time = Date().timeIntervalSince1970 return UInt32(time); }) let callbackFunc: on_log_producer_send_done_function = {config_name,result,log_bytes,compressed_bytes,req_id,error_message,raw_buffer,user_param in let res = LogProducerResult(rawValue: Int(result)) // print(res!) // let req = String(cString: req_id!) // print(req) // print(log_bytes) // print(compressed_bytes) } client = LogProducerClient(logProducerConfig:config, callback:callbackFunc) // client = LogProducerClient(logProducerConfig:config) ``` -------------------------------- ### Configure LogProducerConfig Compression Type Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Set the compression type for logs. LZ4 is the default (1), while 0 means no compression. ```swift config.setCompressType(1) ``` -------------------------------- ### SLSTracer Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Provides OpenTelemetry-compliant tracing APIs, supporting Span creation, attribute setting, event recording, exception handling, and automatic instrumentation of NSURLSession network requests. ```APIDOC ## SLSTracer — 链路追踪(OpenTelemetry 兼容) `SLSTracer` 提供符合 OpenTelemetry 规范的链路追踪 API,支持创建 Span、设置属性、记录事件、异常捕获,并支持自动插桩NSURLSession 网络请求。 ```objc #import #import // 方式一:使用 SpanBuilder 精细控制 SLSSpan *span = [[SLSTracer spanBuilder:@"checkout"] setKind:SLSCLIENT] addAttributes:@[ [SLSAttribute of:@"user.id" stringValue:@"user-123"], [SLSAttribute of:@"order.amount" doubleValue:99.9], [SLSAttribute of:@"order.items" intValue:3] ]] build]; // 设置父 Span(手动传播上下文) // [spanBuilder setParent:parentSpan]; // 添加事件节点 [span addEvent:@"payment_started"]; [span addEvent:@"payment_completed" attributes:@[ [SLSAttribute of:@"payment.method" stringValue:@"Alipay"] ]]; // 记录异常 @try { // 业务逻辑 } @catch (NSException *e) { [span recordException:e attributes:@[ [SLSAttribute of:@"retry.count" intValue:1] ]]; span.statusCode = ERROR; span.statusMessage = e.reason; } [span end]; // 必须调用 end,否则数据不会上报 // 方式二:Block 作用域(自动 end) [SLSTracer withinSpan:@"database_query" active:YES block:^{ // Block 内的代码被自动包裹在一个 Span 中 // 执行完毕后 Span 自动结束 [self fetchUserFromDB:@"user-123"]; }]; // 方式三:快速创建并激活为当前 Span SLSSpan *activeSpan = [SLSTracer startSpan:@"api_call" active:YES]; // ... 业务逻辑 ... [activeSpan end]; // 上报日志(Logs 信号,与 Trace 关联) [SLSTracer log:@"订单创建成功" :SLSLogsLevelInfo]; // NSURLSession 自动插桩委托(过滤特定请求) [SLSTracer registerURLSessionInstrumentationDelegate:self]; // 实现协议: // - (BOOL)shouldInstrument:(NSURLRequest *)request { // return [request.URL.host hasSuffix:@"aliyuncs.com"]; // } ``` ``` -------------------------------- ### SLSCredentials Source: https://context7.com/aliyun/aliyun-log-ios-sdk/llms.txt Manages access credentials for various modules, supporting AccessKey and STS Token authentication, with dynamic runtime refresh capabilities. ```APIDOC ## SLSCredentials — 凭证管理 `SLSCredentials` 统一管理各模块的访问凭证,支持 AccessKey 和 STS Token 两种鉴权方式,并支持运行时动态刷新。 ```objc #import // 创建基础凭证 SLSCredentials *credentials = [SLSCredentials credentials]; credentials.instanceId = @"your-instance-id"; credentials.endpoint = @"https://cn-hangzhou.log.aliyuncs.com"; credentials.project = @"my-project"; credentials.accessKeyId = @"YOUR_AK_ID"; credentials.accessKeySecret = @"YOUR_AK_SECRET"; // STS 临时凭证(可选) credentials.securityToken = @"your-sts-token"; // 为网络诊断模块创建独立凭证 SLSNetworkDiagnosisCredentials *ndCreds = [credentials createNetworkDiagnosisCredentials]; ndCreds.logstore = @"nd-logstore"; ndCreds.secretKey = @"nd-secret-key"; // 网络诊断专用密钥 ndCreds.siteId = @"site-001"; [ndCreds putExtension:@"cn-hangzhou" forKey:@"region"]; // 为链路追踪模块创建独立凭证 SLSTraceCredentials *traceCreds = [credentials createTraceCredentials]; traceCreds.logstore = @"trace-logstore"; // 为 Trace 下的 Logs 信号创建独立 logstore SLSLogsCredentials *logsCreds = [traceCreds createLogsCredentials]; logsCreds.logstore = @"logs-logstore"; // STS Token 过期后动态刷新(无需重启 SDK) // 在 STS Token 即将过期时注册回调更新凭证 [[SLSCocoa sharedInstance] registerCredentialsCallback:^(NSString *feature, NSString *result) { // feature: 触发刷新的功能模块名称 // 拉取新 Token 后刷新 SLSCredentials *newCreds = [SLSCredentials credentials]; newCreds.accessKeyId = @"NEW_STS_KEY_ID"; newCreds.accessKeySecret = @"NEW_STS_KEY_SECRET"; newCreds.securityToken = @"NEW_STS_TOKEN"; [[SLSCocoa sharedInstance] setCredentials:newCreds]; }]; ``` ```