跳到主要内容

导出日志

导出保留的 File 或 XLFacility 日志,并从 App 分享生成的文件 URL。

前提条件

  • 当前输出目标为 .file.xlfacility
  • 选择 .xlfacility 时已安装 XLFacility 插件。
  • 至少存在一条保留日志。

API 参考

框架

AIBudsLog.xcframework

声明

Swift
/// Exports all retained logs to one file.
/// - Parameter completion: Called with the exported path, optional beginning
///   and ending timestamps, and an error.
func exportLogs(_ completion: ((
                    _ filePath: String?,
                    _ logStartFrom: Date?,
                    _ logEndAt: Date?,
                    _ error: NSError?
                ) -> Void)?)

/// Exports retained logs to size-limited files.
/// - Parameters:
///   - maxFileSize: Maximum size of each exported file, in bytes.
///   - completion: Called with exported paths, optional beginning and ending
///     timestamps, and an error.
func exportLogs(_ maxFileSize: UInt64,
                   completion: ((
                       _ filePaths: [String]?,
                       _ logStartFrom: Date?,
                       _ logEndAt: Date?,
                       _ error: NSError?
                   ) -> Void)?)

两项操作均由 LogService 定义,并在 logService 上调用。

使用示例

导出单个文件

Swift
AIBudsLogSDK.logService.exportLogs { filePath, startDate, endDate, error in
    DispatchQueue.main.async {
        if let error {
            print("Export failed: \(error.localizedDescription)")
            return
        }

        guard let filePath else {
            print("Export completed without a file")
            return
        }

        print("Log range: \(String(describing: startDate)) — \(String(describing: endDate))")
        presentShareSheet(items: [URL(fileURLWithPath: filePath)])
    }
}

导出限制大小的文件

Swift
let fiveMegabytes: UInt64 = 5 * 1_000_000
AIBudsLogSDK.logService.exportLogs(fiveMegabytes) { paths, _, _, error in
    guard error == nil, let paths, !paths.isEmpty else { return }
    let URLs = paths.map(URL.init(fileURLWithPath:))
    DispatchQueue.main.async { presentShareSheet(items: URLs) }
}

注意事项

  • maxFileSize 以字节为单位。Demo 使用每 MB 1_000_000 字节换算十进制 MB。
  • .console.oslogger 不支持导出;收集日志前请切换到持久化输出目标。
  • 即使返回了路径,只要存在错误就视为失败;空路径集合表示没有导出产物。
  • 在主线程展示 UIActivityViewController,并在 iPad 上配置其 popover 来源。