You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

227 lines
7.7 KiB

  1. //
  2. // NetworkActivityLogger.swift
  3. // AlamofireNetworkActivityLogger
  4. //
  5. // The MIT License (MIT)
  6. //
  7. // Copyright (c) 2016 Konstantin Kabanov
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in all
  17. // copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  25. // SOFTWARE.
  26. import Alamofire
  27. import Foundation
  28. /// The level of logging detail.
  29. public enum NetworkActivityLoggerLevel {
  30. /// Do not log requests or responses.
  31. case off
  32. /// Logs HTTP method, URL, header fields, & request body for requests, and status code, URL, header fields, response string, & elapsed time for responses.
  33. case debug
  34. /// Logs HTTP method & URL for requests, and status code, URL, & elapsed time for responses.
  35. case info
  36. /// Logs HTTP method & URL for requests, and status code, URL, & elapsed time for responses, but only for failed requests.
  37. case warn
  38. /// Equivalent to `.warn`
  39. case error
  40. /// Equivalent to `.off`
  41. case fatal
  42. }
  43. /// `NetworkActivityLogger` logs requests and responses made by Alamofire.SessionManager, with an adjustable level of detail.
  44. public class NetworkActivityLogger {
  45. // MARK: - Properties
  46. /// The shared network activity logger for the system.
  47. public static let shared = NetworkActivityLogger()
  48. /// The level of logging detail. See NetworkActivityLoggerLevel enum for possible values. .info by default.
  49. public var level: NetworkActivityLoggerLevel
  50. /// Omit requests which match the specified predicate, if provided.
  51. public var filterPredicate: NSPredicate?
  52. private var startDates: [URLSessionTask: Date]
  53. // MARK: - Internal - Initialization
  54. init() {
  55. level = .info
  56. startDates = [URLSessionTask: Date]()
  57. }
  58. deinit {
  59. stopLogging()
  60. }
  61. // MARK: - Logging
  62. /// Start logging requests and responses.
  63. public func startLogging() {
  64. stopLogging()
  65. let notificationCenter = NotificationCenter.default
  66. notificationCenter.addObserver(
  67. self,
  68. selector: #selector(NetworkActivityLogger.networkRequestDidStart(notification:)),
  69. name: Notification.Name.Task.DidResume,
  70. object: nil
  71. )
  72. notificationCenter.addObserver(
  73. self,
  74. selector: #selector(NetworkActivityLogger.networkRequestDidComplete(notification:)),
  75. name: Notification.Name.Task.DidComplete,
  76. object: nil
  77. )
  78. }
  79. /// Stop logging requests and responses.
  80. public func stopLogging() {
  81. NotificationCenter.default.removeObserver(self)
  82. }
  83. // MARK: - Private - Notifications
  84. @objc private func networkRequestDidStart(notification: Notification) {
  85. guard let userInfo = notification.userInfo,
  86. let task = userInfo[Notification.Key.Task] as? URLSessionTask,
  87. let request = task.originalRequest,
  88. let httpMethod = request.httpMethod,
  89. let requestURL = request.url
  90. else {
  91. return
  92. }
  93. if let filterPredicate = filterPredicate, filterPredicate.evaluate(with: request) {
  94. return
  95. }
  96. startDates[task] = Date()
  97. switch level {
  98. case .debug:
  99. logDivider()
  100. print("\(httpMethod) '\(requestURL.absoluteString)':")
  101. if let httpHeadersFields = request.allHTTPHeaderFields {
  102. logHeaders(headers: httpHeadersFields)
  103. }
  104. if let httpBody = request.httpBody, let httpBodyString = String(data: httpBody, encoding: .utf8) {
  105. print(httpBodyString)
  106. }
  107. case .info:
  108. logDivider()
  109. print("\(httpMethod) '\(requestURL.absoluteString)'")
  110. default:
  111. break
  112. }
  113. }
  114. @objc private func networkRequestDidComplete(notification: Notification) {
  115. guard let sessionDelegate = notification.object as? SessionDelegate,
  116. let userInfo = notification.userInfo,
  117. let task = userInfo[Notification.Key.Task] as? URLSessionTask,
  118. let request = task.originalRequest,
  119. let httpMethod = request.httpMethod,
  120. let requestURL = request.url
  121. else {
  122. return
  123. }
  124. if let filterPredicate = filterPredicate, filterPredicate.evaluate(with: request) {
  125. return
  126. }
  127. var elapsedTime: TimeInterval = 0.0
  128. if let startDate = startDates[task] {
  129. elapsedTime = Date().timeIntervalSince(startDate)
  130. startDates[task] = nil
  131. }
  132. if let error = task.error {
  133. switch level {
  134. case .debug, .info, .warn, .error:
  135. logDivider()
  136. print("[Error] \(httpMethod) '\(requestURL.absoluteString)' [\(String(format: "%.04f", elapsedTime)) s]:")
  137. print(error)
  138. default:
  139. break
  140. }
  141. } else {
  142. guard let response = task.response as? HTTPURLResponse else {
  143. return
  144. }
  145. switch level {
  146. case .debug:
  147. logDivider()
  148. print("\(String(response.statusCode)) '\(requestURL.absoluteString)' [\(String(format: "%.04f", elapsedTime)) s]:")
  149. logHeaders(headers: response.allHeaderFields)
  150. guard let data = sessionDelegate[task]?.delegate.data else { break }
  151. do {
  152. let jsonObject = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
  153. let prettyData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
  154. if let prettyString = String(data: prettyData, encoding: .utf8) {
  155. print(prettyString)
  156. }
  157. } catch {
  158. if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
  159. print(string)
  160. }
  161. }
  162. case .info:
  163. logDivider()
  164. print("\(String(response.statusCode)) '\(requestURL.absoluteString)' [\(String(format: "%.04f", elapsedTime)) s]")
  165. default:
  166. break
  167. }
  168. }
  169. }
  170. }
  171. private extension NetworkActivityLogger {
  172. func logDivider() {
  173. print("---------------------")
  174. }
  175. func logHeaders(headers: [AnyHashable : Any]) {
  176. print("Headers: [")
  177. for (key, value) in headers {
  178. print(" \(key) : \(value)")
  179. }
  180. print("]")
  181. }
  182. }