feat: 完善 Release 接口日志与未报备提示
This commit is contained in:
@@ -40,7 +40,7 @@ final class APIClient {
|
||||
appVersion: String = AppClientInfo.appVersion(),
|
||||
osType: String = AppClientInfo.osType,
|
||||
notificationCenter: NotificationCenter = .default,
|
||||
debugLogSink: @escaping (String) -> Void = { print($0) },
|
||||
debugLogSink: @escaping (String) -> Void = APIConsoleDiagnostics.write,
|
||||
droneDockLogSink: @escaping (String) -> Void = DroneDockDiagnostics.write
|
||||
) {
|
||||
self.environment = environment
|
||||
@@ -135,6 +135,7 @@ 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
|
||||
}
|
||||
@@ -182,8 +183,10 @@ final class APIClient {
|
||||
logCancelled(for: request, reason: "URLError.cancelled")
|
||||
throw CancellationError()
|
||||
}
|
||||
logFailure(for: request, error: error)
|
||||
throw APIError.networkFailed(networkErrorMessage(for: error))
|
||||
} catch {
|
||||
logFailure(for: request, error: error)
|
||||
throw APIError.networkFailed(error.localizedDescription)
|
||||
}
|
||||
|
||||
@@ -192,6 +195,7 @@ 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
|
||||
}
|
||||
@@ -254,8 +258,10 @@ final class APIClient {
|
||||
logCancelled(for: request, reason: "URLError.cancelled")
|
||||
throw CancellationError()
|
||||
}
|
||||
logFailure(for: request, error: error)
|
||||
throw APIError.networkFailed(networkErrorMessage(for: error))
|
||||
} catch {
|
||||
logFailure(for: request, error: error)
|
||||
throw APIError.networkFailed(error.localizedDescription)
|
||||
}
|
||||
|
||||
@@ -264,6 +270,7 @@ 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
|
||||
}
|
||||
@@ -415,9 +422,8 @@ final class APIClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// 在 Debug 环境打印请求信息(含 GET 查询参数与 POST 请求体,对齐 Android Ktor `LogLevel.BODY`)。
|
||||
/// Debug/Release 均打印请求地址、参数、请求头和正文。
|
||||
private func logRequest(_ request: URLRequest, includeBody: Bool = true, category: String? = nil) {
|
||||
#if DEBUG
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.request(request, category: category, includeBody: includeBody))
|
||||
return
|
||||
@@ -425,6 +431,9 @@ final class APIClient {
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
var lines = ["[API][Request] \(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 {
|
||||
@@ -443,13 +452,11 @@ final class APIClient {
|
||||
}
|
||||
|
||||
debugLogSink(lines.joined(separator: "\n"))
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 在 Debug 环境打印响应状态和响应体。
|
||||
/// Debug/Release 均打印响应状态、响应头及完整正文,包括非成功响应。
|
||||
private func logResponse(for request: URLRequest, response: URLResponse, data: Data,
|
||||
includeBody: Bool = true, category: String? = nil) {
|
||||
#if DEBUG
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.response(for: request, response: response, data: data,
|
||||
category: category, includeBody: includeBody))
|
||||
@@ -459,13 +466,14 @@ final class APIClient {
|
||||
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>"
|
||||
debugLogSink("[API][Response] \(method) \(url) status=\(statusCode)\n\(body)")
|
||||
#endif
|
||||
let headers = (response as? HTTPURLResponse)?.allHeaderFields.reduce(into: [String: String]()) {
|
||||
$0[String(describing: $1.key)] = String(describing: $1.value)
|
||||
} ?? [:]
|
||||
debugLogSink("[API][Response] \(method) \(url) status=\(statusCode)\nheaders: \(DroneDockDiagnostics.json(headers))\n\(body)")
|
||||
}
|
||||
|
||||
/// 在 Debug 环境打印被取消的请求信息。
|
||||
/// Debug/Release 均记录取消,取消不记作成功响应或网络失败。
|
||||
private func logCancelled(for request: URLRequest, reason: String, category: String? = nil) {
|
||||
#if DEBUG
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.event("Cancelled", for: request, category: category) + " reason=\(reason)")
|
||||
return
|
||||
@@ -473,20 +481,20 @@ final class APIClient {
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
debugLogSink("[API][Cancelled] \(method) \(url) reason=\(reason)")
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 记录已开启模块日志的传输失败,只输出错误域和错误码,避免错误描述夹带凭证。
|
||||
private func logFailure(for request: URLRequest, error: Error, category: String?) {
|
||||
#if DEBUG
|
||||
guard let category else { return }
|
||||
/// 所有业务模块均记录传输、业务拒绝或解码失败;保留显式模块日志策略。
|
||||
private func logFailure(for request: URLRequest, error: Error, category: String? = nil) {
|
||||
let error = error as NSError
|
||||
debugLogSink(APIRedactedLog.event("Failure", for: request, category: category)
|
||||
+ " error=\(error.domain)(\(error.code))")
|
||||
#endif
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.event("Failure", for: request, category: category)
|
||||
+ " error=\(error.domain)(\(error.code))")
|
||||
} else {
|
||||
debugLogSink("[API][Failure] \(request.httpMethod ?? "REQUEST") \(request.url?.absoluteString ?? "<invalid url>")"
|
||||
+ " error=\(error.domain)(\(error.code)) message=\(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// 将请求体格式化为便于调试阅读的字符串。
|
||||
private static func debugRequestBody(from data: Data?, contentType: String?) -> String? {
|
||||
guard let data, !data.isEmpty else { return nil }
|
||||
@@ -503,7 +511,7 @@ final class APIClient {
|
||||
}
|
||||
|
||||
if let text = String(data: data, encoding: .utf8), !text.isEmpty {
|
||||
return text.count > 2_000 ? String(text.prefix(2_000)) + "..." : text
|
||||
return text
|
||||
}
|
||||
|
||||
return "<non-utf8 body: \(data.count) bytes>"
|
||||
@@ -520,7 +528,6 @@ final class APIClient {
|
||||
}
|
||||
return String(data: data, encoding: .utf8) ?? "<non-utf8 response: \(data.count) bytes>"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private extension String {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
|
||||
/// 其他业务模块的统一控制台出口,Debug 和 Release 均通过系统日志完整分段输出。
|
||||
enum APIConsoleDiagnostics {
|
||||
private static let logger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "API")
|
||||
private static let sessionID = String(UUID().uuidString.prefix(8))
|
||||
|
||||
/// 不依赖调试构建或 stdout;复用 UTF-8 分段规则,避免长 JSON 被系统截断。
|
||||
static func write(_ message: String) {
|
||||
let entry = String(UUID().uuidString.prefix(8))
|
||||
let chunks = DroneDockDiagnostics.chunks(message)
|
||||
for (index, chunk) in chunks.enumerated() {
|
||||
let line = "[API] session=\(sessionID) entry=\(entry) part=\(index + 1)/\(chunks.count) \(chunk)"
|
||||
logger.notice("\(line, privacy: .public)")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user