fix: 精简接口日志并补充已支付航拍订单退款入口
统一 HTTP 和 WebSocket 控制台 JSON 输出,保留完整入参、响应及本地错误。为多点位航拍订单增加已支付退款入口和回归测试,并同步联调文档、接口记录及截图。
This commit is contained in:
@@ -98,20 +98,20 @@ final class APIClient {
|
||||
(data, response) = try await session.data(for: request)
|
||||
} catch is CancellationError {
|
||||
if let trace { droneDockLogSink(trace.message("request.cancelled")) }
|
||||
else { logCancelled(for: request, reason: "CancellationError", category: apiRequest.redactedLogCategory) }
|
||||
else { logCancelled(for: request, reason: "CancellationError", category: apiRequest.redactedLogCategory, includeBody: apiRequest.logsPayload) }
|
||||
throw CancellationError()
|
||||
} catch let error as URLError {
|
||||
if let trace { droneDockLogSink(trace.message(error.code == .cancelled ? "request.cancelled" : "request.failed",
|
||||
fields: DroneDockDiagnostics.errorFields(error))) }
|
||||
if error.code == .cancelled {
|
||||
if trace == nil { logCancelled(for: request, reason: "URLError.cancelled", category: apiRequest.redactedLogCategory) }
|
||||
if trace == nil { logCancelled(for: request, reason: "URLError.cancelled", category: apiRequest.redactedLogCategory, includeBody: apiRequest.logsPayload) }
|
||||
throw CancellationError()
|
||||
}
|
||||
if trace == nil { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory) }
|
||||
if trace == nil { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory, includeBody: apiRequest.logsPayload) }
|
||||
throw APIError.networkFailed(networkErrorMessage(for: error))
|
||||
} catch {
|
||||
if let trace { droneDockLogSink(trace.message("request.failed", fields: DroneDockDiagnostics.errorFields(error))) }
|
||||
if trace == nil { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory) }
|
||||
if trace == nil { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory, includeBody: apiRequest.logsPayload) }
|
||||
throw APIError.networkFailed(error.localizedDescription)
|
||||
}
|
||||
|
||||
@@ -135,7 +135,6 @@ final class APIClient {
|
||||
return value
|
||||
} catch let error as APIError {
|
||||
if let trace { droneDockLogSink(trace.message("response.rejected", fields: DroneDockDiagnostics.errorFields(error))) }
|
||||
else { logFailure(for: request, error: error, category: apiRequest.redactedLogCategory) }
|
||||
notifySessionErrorIfNeeded(for: error, request: request)
|
||||
throw error
|
||||
}
|
||||
@@ -195,7 +194,6 @@ final class APIClient {
|
||||
try validateHTTPResponse(response, data: data)
|
||||
return try decodeEnvelope(Response.self, from: data)
|
||||
} catch let error as APIError {
|
||||
logFailure(for: request, error: error)
|
||||
notifySessionErrorIfNeeded(for: error, request: request)
|
||||
throw error
|
||||
}
|
||||
@@ -270,7 +268,6 @@ final class APIClient {
|
||||
try validateHTTPResponse(response, data: responseData)
|
||||
return try decodeEnvelope(Response.self, from: responseData)
|
||||
} catch let error as APIError {
|
||||
logFailure(for: request, error: error)
|
||||
notifySessionErrorIfNeeded(for: error, request: request)
|
||||
throw error
|
||||
}
|
||||
@@ -422,111 +419,43 @@ final class APIClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Debug/Release 均打印请求地址、参数、请求头和正文。
|
||||
/// 发起请求时只打印路径和业务入参,不包含 Header、方法或诊断信封。
|
||||
private func logRequest(_ request: URLRequest, includeBody: Bool = true, category: String? = nil) {
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.request(request, category: category, includeBody: includeBody))
|
||||
return
|
||||
} else {
|
||||
debugLogSink(APIConsoleFormat.message(path: request.url?.path ?? "",
|
||||
params: APIConsoleFormat.parameters(request, includeBody: includeBody)))
|
||||
}
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
var lines = ["\(APIConsoleFormat.prefix("Request", path: request.url?.path ?? "")) \(method) \(url)"]
|
||||
if let headers = request.allHTTPHeaderFields, !headers.isEmpty {
|
||||
lines.append("headers: " + DroneDockDiagnostics.json(headers))
|
||||
}
|
||||
|
||||
if let queryItems = URLComponents(url: request.url ?? URL(fileURLWithPath: "/"), resolvingAgainstBaseURL: false)?.queryItems,
|
||||
!queryItems.isEmpty {
|
||||
let params = queryItems
|
||||
.map { item in
|
||||
let value = item.value ?? ""
|
||||
return "\(item.name)=\(value)"
|
||||
}
|
||||
.joined(separator: "&")
|
||||
lines.append("params: \(params)")
|
||||
}
|
||||
|
||||
let contentType = request.value(forHTTPHeaderField: "Content-Type")
|
||||
if includeBody, let body = Self.debugRequestBody(from: request.httpBody, contentType: contentType) {
|
||||
lines.append("body:\n\(body)")
|
||||
}
|
||||
|
||||
debugLogSink(lines.joined(separator: "\n"))
|
||||
}
|
||||
|
||||
/// Debug/Release 均打印响应状态、响应头及完整正文,包括非成功响应。
|
||||
/// 原始回包整体放入 response,业务失败同样保留完整 JSON,不另打印解析事件。
|
||||
private func logResponse(for request: URLRequest, response: URLResponse, data: Data,
|
||||
includeBody: Bool = true, category: String? = nil) {
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.response(for: request, response: response, data: data,
|
||||
category: category, includeBody: includeBody))
|
||||
return
|
||||
}
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
let statusCode = (response as? HTTPURLResponse).map { String($0.statusCode) } ?? "unknown"
|
||||
let body = includeBody ? Self.debugResponseBody(from: data) : "<sensitive payload omitted>"
|
||||
let headers = (response as? HTTPURLResponse)?.allHeaderFields.reduce(into: [String: String]()) {
|
||||
$0[String(describing: $1.key)] = String(describing: $1.value)
|
||||
} ?? [:]
|
||||
debugLogSink("\(APIConsoleFormat.prefix("Response", path: request.url?.path ?? "")) \(method) \(url) status=\(statusCode)\nheaders: \(DroneDockDiagnostics.json(headers))\n\(body)")
|
||||
}
|
||||
|
||||
/// Debug/Release 均记录取消,取消不记作成功响应或网络失败。
|
||||
private func logCancelled(for request: URLRequest, reason: String, category: String? = nil) {
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.event("Cancelled", for: request, category: category) + " reason=\(reason)")
|
||||
return
|
||||
}
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
debugLogSink("\(APIConsoleFormat.prefix("Cancelled", path: request.url?.path ?? "")) \(method) \(url) reason=\(reason)")
|
||||
}
|
||||
|
||||
/// 所有业务模块均记录传输、业务拒绝或解码失败;保留显式模块日志策略。
|
||||
private func logFailure(for request: URLRequest, error: Error, category: String? = nil) {
|
||||
let error = error as NSError
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.event("Failure", for: request, category: category)
|
||||
+ " error=\(error.domain)(\(error.code))")
|
||||
} else {
|
||||
debugLogSink("\(APIConsoleFormat.prefix("Failure", path: request.url?.path ?? "")) \(request.httpMethod ?? "REQUEST") \(request.url?.absoluteString ?? "<invalid url>")"
|
||||
+ " error=\(error.domain)(\(error.code)) message=\(error.localizedDescription)")
|
||||
debugLogSink(APIConsoleFormat.message(path: request.url?.path ?? "",
|
||||
params: APIConsoleFormat.parameters(request, includeBody: includeBody),
|
||||
response: includeBody ? APIConsoleFormat.payload(data) : "<sensitive payload omitted>"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 将请求体格式化为便于调试阅读的字符串。
|
||||
private static func debugRequestBody(from data: Data?, contentType: String?) -> String? {
|
||||
guard let data, !data.isEmpty else { return nil }
|
||||
|
||||
if let contentType, contentType.lowercased().contains("multipart/form-data") {
|
||||
return "<multipart/form-data: \(data.count) bytes>"
|
||||
}
|
||||
|
||||
if
|
||||
let object = try? JSONSerialization.jsonObject(with: data),
|
||||
let prettyData = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]),
|
||||
let prettyJSON = String(data: prettyData, encoding: .utf8) {
|
||||
return prettyJSON
|
||||
}
|
||||
|
||||
if let text = String(data: data, encoding: .utf8), !text.isEmpty {
|
||||
return text
|
||||
}
|
||||
|
||||
return "<non-utf8 body: \(data.count) bytes>"
|
||||
/// 取消是本地结果,不生成后端业务成功或失败回包。
|
||||
private func logCancelled(for request: URLRequest, reason: String, category: String? = nil, includeBody: Bool = true) {
|
||||
logLocalFailure(for: request, kind: "cancelled", message: "请求已取消", category: category, includeBody: includeBody)
|
||||
}
|
||||
|
||||
/// 将响应体格式化为便于调试阅读的字符串。
|
||||
private static func debugResponseBody(from data: Data) -> String {
|
||||
guard !data.isEmpty else { return "<empty response>" }
|
||||
if
|
||||
let object = try? JSONSerialization.jsonObject(with: data),
|
||||
let prettyData = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]),
|
||||
let prettyJSON = String(data: prettyData, encoding: .utf8) {
|
||||
return prettyJSON
|
||||
}
|
||||
return String(data: data, encoding: .utf8) ?? "<non-utf8 response: \(data.count) bytes>"
|
||||
/// 仅网络层未收到响应时打印本地错误;已经打印原始回包的业务/解析异常不重复输出。
|
||||
private func logFailure(for request: URLRequest, error: Error, category: String? = nil, includeBody: Bool = true) {
|
||||
logLocalFailure(for: request, kind: "network_failed", message: error.localizedDescription, category: category, includeBody: includeBody)
|
||||
}
|
||||
|
||||
private func logLocalFailure(for request: URLRequest, kind: String, message: String, category: String?, includeBody: Bool) {
|
||||
debugLogSink(APIConsoleFormat.failure(path: request.url?.path ?? "",
|
||||
params: category == nil ? APIConsoleFormat.parameters(request, includeBody: includeBody) : APIRedactedLog.parameters(request, includeBody: includeBody),
|
||||
kind: kind, message: message))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,41 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
import OSLog
|
||||
|
||||
/// 其他业务模块的统一控制台出口,Debug 和 Release 均通过系统日志完整分段输出。
|
||||
/// Debug/Release 共用简洁日志出口,序列化输出完整 JSON,避免并发日志互相穿插。
|
||||
enum APIConsoleDiagnostics {
|
||||
private static let logger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "API")
|
||||
private static let sessionID = String(UUID().uuidString.prefix(8))
|
||||
private static let droneDockLogger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "DroneDock")
|
||||
private static let outputLock = NSLock()
|
||||
|
||||
/// 不依赖调试构建或 stdout;复用 UTF-8 分段规则,避免长 JSON 被系统截断。
|
||||
/// Xcode 附加调试时输出一个完整 JSON;脱离调试器时继续写入系统日志。
|
||||
static func write(_ message: String) {
|
||||
let entry = String(UUID().uuidString.prefix(8))
|
||||
for line in APIConsoleFormat.lines(message, sessionID: sessionID, entryID: entry,
|
||||
fallbackModule: "通用接口") {
|
||||
logger.notice("\(line, privacy: .public)")
|
||||
output(message, logger: logger)
|
||||
}
|
||||
|
||||
/// 保留机巢原有系统日志 category,正文格式与其它模块一致。
|
||||
static func writeDroneDock(_ message: String) {
|
||||
output(message, logger: droneDockLogger)
|
||||
}
|
||||
|
||||
private static func output(_ message: String, logger: Logger) {
|
||||
guard let text = APIConsoleFormat.render(message) else { return }
|
||||
outputLock.lock()
|
||||
defer { outputLock.unlock() }
|
||||
if isDebuggerAttached || isatty(STDOUT_FILENO) != 0 {
|
||||
// 不受系统日志单条长度限制,也不受 DEBUG 编译条件影响。
|
||||
FileHandle.standardOutput.write(Data((text + "\n").utf8))
|
||||
} else {
|
||||
// 保留独立运行 Release 包的系统日志可见性,不加 session/entry/part 等包装。
|
||||
for chunk in DroneDockDiagnostics.chunks(text) { logger.notice("\(chunk, privacy: .public)") }
|
||||
}
|
||||
}
|
||||
|
||||
private static var isDebuggerAttached: Bool {
|
||||
var info = kinfo_proc()
|
||||
var size = MemoryLayout<kinfo_proc>.stride
|
||||
var name: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
|
||||
return sysctl(&name, 4, &info, &size, nil, 0) == 0
|
||||
&& (info.kp_proc.p_flag & P_TRACED) != 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,102 +1,91 @@
|
||||
import Foundation
|
||||
|
||||
/// 控制台统一使用中文业务模块标签;只格式化输出,不修改请求和响应内容。
|
||||
/// 控制台只展示路径、入参及原始返回 JSON,不输出诊断信封或业务事件。
|
||||
enum APIConsoleFormat {
|
||||
/// 根据接口路径匹配业务模块;共享接口按自身职责命名,未知接口保留通用标签。
|
||||
static func module(for path: String) -> String {
|
||||
let routes: [(String, String)] = [
|
||||
("/api/app/airport", "机巢工作台"),
|
||||
("/api/app/order-flight-task", "机巢工作台"),
|
||||
("/api/yf-handset-app/photog/multi-plane", "机巢工作台"),
|
||||
("/api/app/scenic-media", "景区空境库"),
|
||||
("/api/app/config/get-sts-token", "文件上传"),
|
||||
("/api/app/scenic-queue", "景区排队"),
|
||||
("/api/app/socket-token", "消息连接"),
|
||||
("/api/app/manual-live", "直播"),
|
||||
("/api/app/view-album", "直播素材"),
|
||||
("/api/app/media-album", "样片管理"),
|
||||
("/api/app/msg", "消息中心"),
|
||||
("/api/app/user/register-jpush-id", "消息推送"),
|
||||
("/api/app/training", "培训"),
|
||||
("/api/app/store/order", "订单"),
|
||||
("/api/app/scenic-admin/order", "订单"),
|
||||
("/api/app/store/analyse", "数据统计"),
|
||||
("/api/app/scenic-admin/analyse", "数据统计"),
|
||||
("/api/app/store", "门店"),
|
||||
("/api/app/v9", "账号登录"),
|
||||
("/api/yf-handset-app/account-deregister", "账号注销"),
|
||||
("/api/yf-handset-app/photog/order", "订单"),
|
||||
("/api/yf-handset-app/photog/task", "拍摄任务"),
|
||||
("/api/yf-handset-app/photog/analyse", "数据统计"),
|
||||
("/api/yf-handset-app/photog/cloud-driver", "云存储"),
|
||||
("/api/yf-handset-app/photog/travel-album", "旅拍相册"),
|
||||
("/api/yf-handset-app/photog/wallet", "钱包"),
|
||||
("/api/yf-handset-app/photog/point", "积分"),
|
||||
("/api/yf-handset-app/photog/scenic-spot", "打卡点"),
|
||||
("/api/yf-handset-app/photog/scenic", "景区"),
|
||||
("/api/yf-handset-app/photog/scenic-apply", "景区入驻"),
|
||||
("/api/yf-handset-app/photog/role-apply", "角色申请"),
|
||||
("/api/yf-handset-app/photog/loacation", "位置上报"),
|
||||
("/api/yf-handset-app/photog/report", "摄影师举报"),
|
||||
("/api/yf-handset-app/photog/sale-user", "销售员"),
|
||||
("/api/yf-handset-app/photog/cooperative-salers", "销售员"),
|
||||
("/api/yf-handset-app/photog/invite", "邀请"),
|
||||
("/api/yf-handset-app/photog/invite-info", "邀请"),
|
||||
("/api/yf-handset-app/photog/project", "套餐"),
|
||||
("/api/yf-handset-app/photog/offline-pay-collect", "线下收款"),
|
||||
("/api/yf-handset-app/photog/pay-code", "收款"),
|
||||
("/api/yf-handset-app/photog/pay-page-config", "收款"),
|
||||
("/api/yf-handset-app/photog/real-name", "实名认证"),
|
||||
("/api/yf-handset-app/photog/profile", "个人资料"),
|
||||
("/api/yf-handset-app/photog/schedule", "个人资料"),
|
||||
("/api/yf-handset-app/photog/userinfo-update-avatar", "个人资料"),
|
||||
("/api/yf-handset-app/userinfo", "个人资料"),
|
||||
("/api/yf-handset-app/userinfo-update", "个人资料"),
|
||||
("/api/yf-handset-app/userinfo-update-avatar-url", "个人资料"),
|
||||
("/api/yf-handset-app/role-permission", "账号权限"),
|
||||
("/api/app/config", "系统配置"),
|
||||
("/api/app/latest-version", "版本更新")
|
||||
]
|
||||
return routes.first { path == $0.0 || path.hasPrefix($0.0 + "/") }?.1 ?? "通用接口"
|
||||
/// 发起请求时立即输出路径和参数;响应记录携带同样参数,方便并发请求核对。
|
||||
static func message(path: String, params: Any, response: Any? = nil) -> String {
|
||||
var values: [(String, Any)] = [("path", path), ("params", params)]
|
||||
if let response { values.append(("response", response)) }
|
||||
let fields = values.map { key, value in
|
||||
" \"\(key)\": " + pretty(value).replacingOccurrences(of: "\n", with: "\n ")
|
||||
}
|
||||
return "{\n" + fields.joined(separator: ",\n") + "\n}"
|
||||
}
|
||||
|
||||
/// 请求、响应以及明确失败/取消使用同一标签结构,模块可由调用方显式指定。
|
||||
static func prefix(_ event: String, path: String, category: String? = nil) -> String {
|
||||
"【\(category ?? module(for: path))-\(event)】"
|
||||
}
|
||||
|
||||
/// 为每个完整分段重复添加模块标签,保留正文、会话、事件 ID 及分段顺序。
|
||||
static func lines(_ message: String, sessionID: String, entryID: String,
|
||||
fallbackModule: String) -> [String] {
|
||||
let tag: String
|
||||
let body: String
|
||||
if message.hasPrefix("【"), let end = message.firstIndex(of: "】") {
|
||||
tag = String(message[...end])
|
||||
let remainder = message[message.index(after: end)...]
|
||||
body = remainder.hasPrefix(" ") ? String(remainder.dropFirst()) : String(remainder)
|
||||
} else if let fields = try? JSONSerialization.jsonObject(with: Data(message.utf8)) as? [String: Any] {
|
||||
let event = fields["event"] as? String ?? ""
|
||||
let module: String
|
||||
if event.hasPrefix("file_download.") { module = "素材下载" }
|
||||
else if event.hasPrefix("file_upload.") { module = "成片上传" }
|
||||
else if let path = fields["path"] as? String { module = Self.module(for: path) }
|
||||
else { module = fallbackModule }
|
||||
let kind: String
|
||||
if event.hasSuffix("request.started") { kind = "Request" }
|
||||
else if event.hasSuffix("response.received") { kind = "Response" }
|
||||
else if event.hasSuffix("request.cancelled") { kind = "Cancelled" }
|
||||
else if event.hasSuffix("request.failed") || event.hasSuffix("response.rejected") { kind = "Failure" }
|
||||
else if event.hasSuffix("request.blocked") { kind = "Blocked" }
|
||||
else { kind = "Event" }
|
||||
tag = "【\(module)-\(kind)】"
|
||||
body = message
|
||||
/// 从真正发送的 URLRequest 读取业务入参,不混入 Header 或环境配置。
|
||||
static func parameters(_ request: URLRequest, includeBody: Bool = true) -> Any {
|
||||
let query = queryParameters(request.url)
|
||||
guard includeBody, let data = request.httpBody, !data.isEmpty else { return query }
|
||||
let body: Any
|
||||
if request.value(forHTTPHeaderField: "Content-Type")?.lowercased().contains("multipart/form-data") == true {
|
||||
// 不读取或打印视频/图片文件内容;multipart 入参以表单元信息表示。
|
||||
body = ["content_type": "multipart/form-data", "bytes": data.count]
|
||||
} else {
|
||||
tag = "【\(fallbackModule)-Event】"
|
||||
body = message
|
||||
body = payload(data)
|
||||
}
|
||||
let chunks = DroneDockDiagnostics.chunks(body)
|
||||
return chunks.enumerated().map { index, chunk in
|
||||
"\(tag) session=\(sessionID) entry=\(entryID) part=\(index + 1)/\(chunks.count) \(chunk)"
|
||||
return query.isEmpty ? body : ["query": query, "body": body]
|
||||
}
|
||||
|
||||
/// 保留重复参数和无值参数,避免诊断时丢失实际请求内容。
|
||||
static func queryParameters(_ url: URL?) -> [String: Any] {
|
||||
let items = url.flatMap { URLComponents(url: $0, resolvingAgainstBaseURL: false)?.queryItems } ?? []
|
||||
var result: [String: Any] = [:]
|
||||
for item in items {
|
||||
let value: Any = item.value as Any? ?? NSNull()
|
||||
if let previous = result[item.name] {
|
||||
result[item.name] = (previous as? [Any] ?? [previous]) + [value]
|
||||
} else { result[item.name] = value }
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// 保留完整 JSON 类型;空正文为 null,非 JSON 文本作为字符串显示。
|
||||
static func payload(_ data: Data) -> Any {
|
||||
guard !data.isEmpty else { return NSNull() }
|
||||
return (try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed))
|
||||
?? String(data: data, encoding: .utf8) as Any? ?? ["binary_bytes": data.count]
|
||||
}
|
||||
|
||||
/// 本地失败没有后端响应,明确使用 local_error,避免伪装成后端业务返回。
|
||||
static func failure(path: String, params: Any, kind: String, message: String) -> String {
|
||||
self.message(path: path, params: params, response: ["local_error": ["kind": kind, "message": message]])
|
||||
}
|
||||
|
||||
/// 将内部诊断记录转换为简洁输出;解码、页面、心跳、RTC 等事件不进入控制台。
|
||||
static func render(_ text: String) -> String? {
|
||||
guard let fields = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] else { return nil }
|
||||
if fields["event"] == nil, let path = fields["path"] as? String, let params = fields["params"] {
|
||||
return message(path: path, params: params, response: fields["response"])
|
||||
}
|
||||
let event = fields["event"] as? String ?? ""
|
||||
let isRequest = event.hasSuffix("request.started")
|
||||
let isResponse = event.hasSuffix("response.received")
|
||||
let isFailed = event.hasSuffix("request.failed")
|
||||
let isCancelled = event.hasSuffix("request.cancelled")
|
||||
let isBlocked = event.hasSuffix("request.blocked")
|
||||
guard isRequest || isResponse || isFailed || isCancelled || isBlocked else { return nil }
|
||||
let url = (fields["url"] as? String).flatMap(URL.init(string:))
|
||||
guard let path = fields["path"] as? String ?? url?.path else { return nil }
|
||||
var params: Any = fields["request_params"] ?? queryParameters(url)
|
||||
if fields["request_params"] == nil, isRequest, let body = fields["body"], body as? String != "<empty>" {
|
||||
params = body
|
||||
}
|
||||
if event.hasPrefix("file_upload."), isRequest {
|
||||
params = fields.filter { ["bucket", "object_key", "bytes", "content_type"].contains($0.key) }
|
||||
}
|
||||
if isRequest { return message(path: path, params: params) }
|
||||
if isResponse {
|
||||
let body = fields["body"] ?? fields["bytes"].map { ["binary_bytes": $0] } as Any? ?? NSNull()
|
||||
return message(path: path, params: params, response: body as? String == "<empty>" ? NSNull() : body)
|
||||
}
|
||||
let kind = isBlocked ? "blocked" : isCancelled ? "cancelled" : "network_failed"
|
||||
let reason = fields["message"] as? String ?? (isBlocked ? "请求已在本地拦截,未发送" : isCancelled ? "请求已取消" : "请求失败,未收到响应")
|
||||
return failure(path: path, params: params, kind: kind, message: reason)
|
||||
}
|
||||
|
||||
private static func pretty(_ value: Any) -> String {
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: value,
|
||||
options: [.prettyPrinted, .sortedKeys, .fragmentsAllowed, .withoutEscapingSlashes]) else { return "null" }
|
||||
return String(decoding: data, as: UTF8.self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +1,28 @@
|
||||
import Foundation
|
||||
|
||||
/// 按模块生成可读的调试日志;只处理输出副本,不修改网络请求和业务响应。
|
||||
/// 沿用接口指定的正文脱敏策略生成简洁 JSON;只处理输出副本,不修改网络请求和响应。
|
||||
nonisolated enum APIRedactedLog {
|
||||
private static let urlPattern = try? NSRegularExpression(pattern: #"https?://[^\s"<>]+"#, options: [.caseInsensitive])
|
||||
|
||||
/// 输出方法、地址、查询参数及可选 JSON 请求体,不输出鉴权 Header。
|
||||
/// 保留接口原有脱敏策略,只修改日志展示结构。
|
||||
static func request(_ request: URLRequest, category: String, includeBody: Bool) -> String {
|
||||
var lines = [event("Request", for: request, category: category)]
|
||||
if let url = request.url,
|
||||
let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems,
|
||||
!items.isEmpty {
|
||||
lines.append("params: " + items.map {
|
||||
"\($0.name)=\(isSensitive($0.name) ? "<redacted>" : redactURLs(in: $0.value ?? ""))"
|
||||
}.joined(separator: "&"))
|
||||
}
|
||||
if includeBody, let data = request.httpBody {
|
||||
lines.append("body:\n" + body(data))
|
||||
}
|
||||
return lines.joined(separator: "\n")
|
||||
APIConsoleFormat.message(path: request.url?.path ?? "", params: parameters(request, includeBody: includeBody))
|
||||
}
|
||||
|
||||
/// 输出 HTTP 状态及格式化的脱敏 JSON,包括业务失败或非 2xx 响应。
|
||||
/// 请求与回包共享参数,响应关闭正文记录时继续遵守原设置。
|
||||
static func response(for request: URLRequest, response: URLResponse, data: Data,
|
||||
category: String, includeBody: Bool) -> String {
|
||||
let status = (response as? HTTPURLResponse).map { String($0.statusCode) } ?? "unknown"
|
||||
let payload = includeBody ? body(data) : "<sensitive payload omitted>"
|
||||
return event("Response", for: request, category: category) + " status=\(status)\n" + payload
|
||||
let payload: Any
|
||||
if !includeBody { payload = "<sensitive payload omitted>" }
|
||||
else if let object = try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) { payload = redact(object) }
|
||||
else { payload = "<non-JSON body omitted: \(data.count) bytes>" }
|
||||
return APIConsoleFormat.message(path: request.url?.path ?? "",
|
||||
params: parameters(request, includeBody: includeBody), response: payload)
|
||||
}
|
||||
|
||||
/// 生成请求、响应、失败和取消共用的模块标签与安全地址。
|
||||
static func event(_ event: String, for request: URLRequest, category: String) -> String {
|
||||
let url = request.url.map { redactedURL($0, keepsQuery: true) } ?? "<invalid url>"
|
||||
return "\(APIConsoleFormat.prefix(event, path: request.url?.path ?? "", category: category)) \(request.httpMethod ?? "REQUEST") \(url)"
|
||||
}
|
||||
|
||||
/// 非 JSON 正文可能包含凭证或服务端调试页面,不把原始文本写入控制台。
|
||||
private static func body(_ data: Data) -> String {
|
||||
guard !data.isEmpty else { return "<empty body>" }
|
||||
guard let object = try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]),
|
||||
let formatted = try? JSONSerialization.data(withJSONObject: redact(object),
|
||||
options: [.prettyPrinted, .sortedKeys, .fragmentsAllowed, .withoutEscapingSlashes]),
|
||||
let text = String(data: formatted, encoding: .utf8) else {
|
||||
return "<non-JSON body omitted: \(data.count) bytes>"
|
||||
}
|
||||
return text
|
||||
/// 脱敏只处理日志副本,原请求不受影响。
|
||||
static func parameters(_ request: URLRequest, includeBody: Bool) -> Any {
|
||||
redact(APIConsoleFormat.parameters(request, includeBody: includeBody))
|
||||
}
|
||||
|
||||
/// 递归处理嵌套对象与数组,保留普通字段、空值及 JSON 类型。
|
||||
|
||||
@@ -23,7 +23,7 @@ nonisolated struct APIRequest<Response: Decodable> {
|
||||
var body: AnyEncodable?
|
||||
/// 控制普通正文日志;机巢范围按用户要求始终记录完整请求和响应。
|
||||
var logsPayload: Bool
|
||||
/// 为指定模块输出带标签的脱敏日志;隐藏凭证字段和响应中媒体 URL 的查询参数。
|
||||
/// 为指定模块启用原有正文脱敏策略;隐藏凭证及媒体 URL 查询参数,不增加控制台标签。
|
||||
var redactedLogCategory: String?
|
||||
|
||||
/// 创建一个 API 请求,并把可编码请求体擦除为统一的 AnyEncodable。
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
|
||||
/// 机巢联调日志:按用户要求在 Debug 与 Release 控制台原样记录字段,不做脱敏。
|
||||
enum DroneDockDiagnostics {
|
||||
private static let logger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "DroneDock")
|
||||
private static let sessionID = String(UUID().uuidString.prefix(8))
|
||||
|
||||
/// 按 UTF-8 字节分段,避免系统日志截断大响应;每段携带同一事件 ID 和序号。
|
||||
/// 与其它模块共用简洁出口;内部诊断事件留作测试/业务核对,不在控制台刷屏。
|
||||
static func write(_ message: String) {
|
||||
let entry = String(UUID().uuidString.prefix(8))
|
||||
for line in APIConsoleFormat.lines(message, sessionID: sessionID, entryID: entry,
|
||||
fallbackModule: "机巢工作台") {
|
||||
logger.notice("\(line, privacy: .public)")
|
||||
}
|
||||
APIConsoleDiagnostics.writeDroneDock(message)
|
||||
}
|
||||
|
||||
/// 页面、业务与 RTC 事件以结构化字段记录。
|
||||
/// 构造内部结构化事件;控制台仅选择请求、响应及本地传输失败输出。
|
||||
static func event(_ name: String, taskID: Int? = nil, fields: [String: Any] = [:]) {
|
||||
var fields = fields
|
||||
fields["task_id"] = taskID
|
||||
@@ -64,7 +56,7 @@ enum DroneDockDiagnostics {
|
||||
return fields
|
||||
}
|
||||
|
||||
/// 单段最多 600 字节,长 JSON 可按 entry 和 part 拼回完整响应。
|
||||
/// 独立运行时的系统日志按最多 600 字节分段;Xcode 控制台直接输出完整 JSON。
|
||||
static func chunks(_ text: String) -> [String] {
|
||||
var result: [String] = []
|
||||
var current = ""
|
||||
@@ -136,6 +128,7 @@ struct DroneDockRequestTrace {
|
||||
fields["method"] = request.httpMethod
|
||||
fields["url"] = request.url?.absoluteString
|
||||
fields["request_headers"] = request.allHTTPHeaderFields ?? [:]
|
||||
fields["request_params"] = APIConsoleFormat.parameters(request)
|
||||
fields["app_version"] = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
|
||||
fields["app_build"] = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
|
||||
#if DEBUG
|
||||
|
||||
Reference in New Issue
Block a user