如何使用Alamofire记录每个请求/响应?

时间:2014-11-04 13:32:44

标签: ios debugging afnetworking-2 alamofire

有没有办法使用Alamofire记录每个请求/响应(类似于AFNetworkActivityLogger)?

我知道Printable,DebugPrintable和Output(cURL),但它们并不是我想要的。

8 个答案:

答案 0 :(得分:41)

这样的事情可能就是你想要的:

extension Request {
   public func debugLog() -> Self {
      #if DEBUG
         debugPrint(self)
      #endif
      return self
   }
}

用法:

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .debugLog()
         .response {…}

如果要打印所有响应,可以编写自己的响应方法,类似于本教程顶部的responseObject()方法:

http://www.raywenderlich.com/87595/intermediate-alamofire-tutorial

[更新:根据@trauzti的要求在下面添加。]

以下是如何使用responseObject()方法在每个请求上打印输出。

警告:我还没有亲自测试过这段代码,可能会在制作中做出不同的选择。这简单地说明了Wenderlich教程代码如何包含调试日志记录。另请注意:由于本教程是Swift 2.0之前的版本,因此我使用了旧的println()而不是print()。

@objc public protocol ResponseObjectSerializable {
  init(response: NSHTTPURLResponse, representation: AnyObject)
}

extension Alamofire.Request {
  public func responseObject<T: ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self {
    let serializer: Serializer = { (request, response, data) in

      #if DEBUG
         println("Request: \(request.URL)")
      #endif

      let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
      let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
      if response != nil && JSON != nil {
        #if DEBUG
           println("Response:")
           debugPrint(JSON)
        #endif

        return (T(response: response!, representation: JSON!), nil)
      } else {
        #if DEBUG
           println("Failed Serialization:")
           debugPrint(serializationError)
        #endif

        return (nil, serializationError)
      }
    }

    return response(serializer: serializer, completionHandler: { (request, response, object, error) in
      completionHandler(request, response, object as? T, error)
    })
  }
}

答案 1 :(得分:31)

这是一个可爱的小豆荚:https://github.com/konkab/AlamofireNetworkActivityLogger

将此添加到您的podfile:

pod 'AlamofireNetworkActivityLogger', '~> 2.0'

在AppDelegate中:

import AlamofireNetworkActivityLogger

然后在didFinishLaunchingWithOptions中添加以下内容:

NetworkActivityLogger.shared.level = .debug
NetworkActivityLogger.shared.startLogging()

编辑: 我在生产中遇到过这种情况。为了安全起见,使用&#34; build flags&#34;只在调试中使用它,如下所示:

#if DEBUG
    NetworkActivityLogger.shared.level = .debug
    NetworkActivityLogger.shared.startLogging()
#endif

答案 2 :(得分:10)

Timberjack正是你所期待的。 Timberjack是一个简单,不引人注目的网络活动记录器。记录您的应用程序发出的每个请求,或者如果您愿意,只限制使用某个NSURLSession的请求。它也适用于Alamofire,如果那是你的事。

https://cocoapods.org/pods/Timberjack

用法:

import Alamofire
import Timberjack

class HTTPManager: Alamofire.Manager {
static let sharedManager: HTTPManager = {
    let configuration = Timberjack.defaultSessionConfiguration()
    let manager = HTTPManager(configuration: configuration)
    return manager
}()
}

答案 3 :(得分:4)

添加到上面的答案 for Alamofire 4.0+ Swift 3

extension DataRequest {        
        public func LogRequest() -> Self {
        //Your logic for logging
        return self
    }
}

申请时

Alamofire.request(requestUrl, method: .post, parameters: parameter, encoding: JSONEncoding.default)
            .LogRequest()
            .responseJSON { response in
            //Do your thing
            }

如果您想在任何情况下取消请求(这是我想要的),您可以在返回自己之前随时随地self.cancel()

答案 4 :(得分:3)

从Alamofire 5开始,最简单的方法是定义一个EventMonitor子类:

final class AlamofireLogger: EventMonitor {
    func requestDidResume(_ request: Request) {
        let body = request.request.flatMap { $0.httpBody.map { String(decoding: $0, as: UTF8.self) } } ?? "None"
        let message = """
        ⚡️ Request Started: \(request)
        ⚡️ Body Data: \(body)
        """
        NSLog(message)
    }

    func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value>) {
        NSLog("⚡️ Response Received: \(response.debugDescription)")
    }
}

然后在您的session上使用它:

let session = Session(eventMonitors: [ AlamofireLogger() ])

此示例代码改编自https://github.com/Alamofire/Alamofire/issues/2867#issuecomment-509662892

答案 5 :(得分:2)

在Alamofire 5中,URLRequest是异步创建的,这意味着

extension Request {
 public func debugLog() -> Self {
  #if DEBUG
     debugPrint(self)
  #endif
  return self
  }
}

不再是最佳解决方案。相反,建议您拨打cURLDescription,如下所示:

let request = AF.request(<Your request>))
request.cURLDescription { (curl) in
   print("CURL \(curl)")
}
request.responseJSON { response in
   //Do something with your response...
}

extension Request {
public func debugLog() -> Self {
    #if DEBUG
    cURLDescription(calling: { (curl) in
        debugPrint("=======================================")
        print(curl)
        debugPrint("=======================================")
    })
    #endif
    return self
  }
 }

答案 6 :(得分:1)

在Alamofire 5.0.0中,我使用的答案基于: https://github.com/Alamofire/Alamofire/issues/2867#issuecomment-509662892 但是我不得不用AFDataResponse代替DataResponse。例如:

import Alamofire

final class AlamofireLogger: EventMonitor {

    func requestDidResume(_ request: Request) {

        let allHeaders = request.request.flatMap { $0.allHTTPHeaderFields.map { $0.description } } ?? "None"
        let headers = """
        ⚡️⚡️⚡️⚡️ Request Started: \(request)
        ⚡️⚡️⚡️⚡️ Headers: \(allHeaders)
        """
        NSLog(headers)


        let body = request.request.flatMap { $0.httpBody.map { String(decoding: $0, as: UTF8.self) } } ?? "None"
        let message = """
        ⚡️⚡️⚡️⚡️ Request Started: \(request)
        ⚡️⚡️⚡️⚡️ Body Data: \(body)
        """
        NSLog(message)
    }

    func request<Value>(_ request: DataRequest, didParseResponse response: AFDataResponse<Value>) {

        NSLog("⚡️⚡️⚡️⚡️ Response Received: \(response.debugDescription)")
        NSLog("⚡️⚡️⚡️⚡️ Response All Headers: \(String(describing: response.response?.allHeaderFields))")
    }
}

然后您可以通过以下方式使用它:

let session = Session(eventMonitors: [ AlamofireLogger() ])

正如前面的帖子中0xced所解释的。

答案 7 :(得分:-1)

SWIFT 3.0 +解决方案

对于Printing Request参数和标题:

Alamofire.request(url, method: .get, parameters: parameters, headers: headers)
            .validate()
            .responseObject { (response: DataResponse<T>) in
                self.pendingRequests.removeValue(forKey: endPoint)
                completion!(response)

                if(NetworkConfig.loggingEnable) {
                    debugPrint("************* printing REQUEST parameter and Headers *************")
                    debugPrint("RESPONSE : \(response.debugDescription)")
                }
        }.responseDebugPrint()

用于打印响应。使用以下扩展名。

import Foundation
import Alamofire

extension Alamofire.DataRequest {
    func responseDebugPrint() -> Self {
        if NetworkConfig.loggingEnable {

            return responseJSON() {
                response in
                if let  JSON = response.result.value,
                    let JSONData = try? JSONSerialization.data(withJSONObject: JSON, options: .prettyPrinted),
                    let prettyString = NSString(data: JSONData, encoding: String.Encoding.utf8.rawValue) {
                    print(prettyString)
                } else if let error = response.result.error {
                    print("Error Debug Print: \(error.localizedDescription)")
                }
            }
        }
        return self
    }
}

小小的要点: https://gist.github.com/manishpathak99/348f2eb0167c0ff6e12ecd667612bc9b/edit