Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- public class NetworkLogger {
- public static let shared = NetworkLogger()
- public func startLogging() {
- let notificationCenter = NotificationCenter.default
- notificationCenter.addObserver(
- self,
- selector: #selector(logRequestInfo),
- name: Notification.Name.Task.DidResume,
- object: nil
- )
- notificationCenter.addObserver(
- self,
- selector: #selector(logRequestInfo),
- name: Notification.Name.Task.DidComplete,
- object: nil
- )
- }
- @objc private func logRequestInfo(_ notification: Notification) {
- guard let userInfo = notification.userInfo,
- let task = userInfo[Notification.Key.Task] as? URLSessionTask,
- let request = task.originalRequest,
- let httpMethod = request.httpMethod
- else { return }
- let requestPath = [request.url?.path, request.url?.query].compactMap { $0 }.joined(separator: "?")
- if let response = task.response as? HTTPURLResponse {
- let message = components(
- httpMethod: httpMethod,
- requestPath: requestPath,
- data: userInfo[Notification.Key.ResponseData] as? Data,
- statusCode: response.statusCode
- )
- print("Finished network request: \(message)")
- } else if let error = task.error {
- let message = components(
- httpMethod: httpMethod,
- requestPath: requestPath,
- data: userInfo[Notification.Key.ResponseData] as? Data
- )
- print("Finished network request: \(message) with errors: \(error)")
- } else {
- let message = components(
- httpMethod: httpMethod,
- requestPath: requestPath,
- data: task.originalRequest?.httpBody
- )
- print("Started network request: \(message)")
- }
- }
- func components(httpMethod: String, requestPath: String, data: Data?, statusCode: Int? = nil) -> String {
- return [
- "AF request",
- "<\(httpMethod)",
- statusCode?.description,
- "\(requestPath)>",
- json(from: data)
- ]
- .compactMap { $0 }
- .joined(separator: " ")
- }
- func json(from data: Data?) -> String? {
- let emptyArray = "[]"
- let emptyDictionary = "{}"
- let converted: String
- if let data = data {
- converted = String(data: data, encoding: .utf8) ?? emptyDictionary
- } else {
- converted = emptyDictionary
- }
- if [emptyDictionary, emptyArray].contains(converted) {
- return "HTTPBody: \(converted);"
- } else {
- return "HTTPBody:\n" + converted
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement