From f78904b8df982ea4bf0f026534a96a5988dbb604 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrej=20Jas=CC=8Cs=CC=8Co?= Date: Tue, 5 Mar 2024 16:12:13 +0100 Subject: [PATCH] fix: optional message publisher --- .../Session/Logger/LoggingEventMonitor.swift | 42 +++++++++++-------- 1 file changed, 25 insertions(+), 17 deletions(-) diff --git a/Sources/GoodNetworking/Session/Logger/LoggingEventMonitor.swift b/Sources/GoodNetworking/Session/Logger/LoggingEventMonitor.swift index 8a20ebc..fd6c1a7 100644 --- a/Sources/GoodNetworking/Session/Logger/LoggingEventMonitor.swift +++ b/Sources/GoodNetworking/Session/Logger/LoggingEventMonitor.swift @@ -16,7 +16,6 @@ public class LoggingEventMonitor: EventMonitor { public static var maxVerboseLogSizeBytes: Int = 100_000 private var messages: PassthroughSubject? - public lazy var messagesPublisher = messages?.eraseToAnyPublisher() public let queue = DispatchQueue(label: C.queueLabel, qos: .background) @@ -26,16 +25,23 @@ public class LoggingEventMonitor: EventMonitor { } - private var logger: (any SessionLogger)? + private var logger: any SessionLogger - public init(logger: (any SessionLogger)?) { + public init(logger: any SessionLogger) { self.logger = logger } + public func subscribeToMessages() -> AnyPublisher { + let messages = PassthroughSubject() + self.messages = messages + return messages.eraseToAnyPublisher() + } + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { - let requestInfoMessage = parseRequestInfo(response: response) + let requestInfoMessage = parseRequestInfo(request: response.request) let metricsMessage = parse(metrics: response.metrics) let requestBodyMessage = parse(data: request.request?.httpBody, error: response.error as NSError?, prefix: "⬆️ Request body:") + let responseStatusMessage = parseResponseStatus(response: response.response) let errorMessage: String? = if let afError = response.error { "🚨 Error:\n\(afError)" } else { @@ -48,23 +54,24 @@ public class LoggingEventMonitor: EventMonitor { "❓❓❓ Response MIME type not whitelisted (\(response.response?.mimeType ?? "❓")). You can try adding it to whitelist using logMimeType(_ mimeType:)." } - let logMessage = [ + let logMessaage = [ requestInfoMessage, metricsMessage, requestBodyMessage, + responseStatusMessage, errorMessage, responseBodyMessage ].compactMap { $0 }.joined(separator: "\n") if let messages { - messages.send(logMessage) + messages.send(logMessaage) } switch response.result { case .success: - logger?.log(level: .debug, message: logMessage) + logger.log(level: .debug, message: logMessaage) case .failure: - logger?.log(level: .fault, message: logMessage) + logger.log(level: .fault, message: logMessaage) } } @@ -72,16 +79,14 @@ public class LoggingEventMonitor: EventMonitor { private extension LoggingEventMonitor { - func parseRequestInfo(response: DataResponse) -> String? { - guard let request = response.request, + func parseRequestInfo(request: URLRequest?) -> String? { + guard let request = request, let url = request.url?.absoluteString.removingPercentEncoding, - let method = request.httpMethod, - let response = response.response - else { + let method = request.httpMethod else { return nil } guard Self.verbose else { - return "🚀 \(method)|\(parseResponseStatus(response: response))|\(url)" + return "🚀 \(method) \(url)" } if let headers = request.allHTTPHeaderFields, @@ -89,7 +94,7 @@ private extension LoggingEventMonitor { let headersData = try? JSONSerialization.data(withJSONObject: headers, options: [.prettyPrinted]), let headersPrettyMessage = parse(data: headersData, error: nil, prefix: "🏷 Headers:") { - return "🚀 \(method)|\(parseResponseStatus(response: response))|\(url)\n" + headersPrettyMessage + return "🚀 \(method) \(url)\n" + headersPrettyMessage } else { let headers = if let allHTTPHeaderFields = request.allHTTPHeaderFields, !allHTTPHeaderFields.isEmpty { allHTTPHeaderFields.description @@ -136,8 +141,11 @@ private extension LoggingEventMonitor { } - func parseResponseStatus(response: HTTPURLResponse) -> String { - let statusCode = response.statusCode + func parseResponseStatus(response: HTTPURLResponse?) -> String? { + guard let statusCode = response?.statusCode else { + return nil + } + let logMessage = (200 ..< 300).contains(statusCode) ? "✅ \(statusCode)" : "❌ \(statusCode)" return logMessage }