3

Is there any way to log my request and response in Moya 14 without using verbose?

container.register(NetworkLoggerPlugin.self) { r in
   NetworkLoggerPlugin(verbose: true)
   }.inObjectScope(.container)

Thank you in advance.

Aira Samson
  • 226
  • 2
  • 10

2 Answers2

8

The initial guidance has been given elsewhere to create a custom plugin for Moya, but here's a working example of a verbose plugin that will display both request and response data.

Add the following code to wherever you are calling Moya from:

struct VerbosePlugin: PluginType {
    let verbose: Bool

    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        #if DEBUG
        if let body = request.httpBody,
           let str = String(data: body, encoding: .utf8) {
            if verbose {
                print("request to send: \(str))")
            }
        }
        #endif
        return request
    }

    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        #if DEBUG
        switch result {
        case .success(let body):
            if verbose {
                print("Response:")
                if let json = try? JSONSerialization.jsonObject(with: body.data, options: .mutableContainers) {
                    print(json)
                } else {
                    let response = String(data: body.data, encoding: .utf8)!
                    print(response)
                }
            }
        case .failure( _):
            break
        }
        #endif
    }

}

In your set up, add the new plugin:

let APIManager = MoyaProvider<API>( plugins: [
    VerbosePlugin(verbose: true)
    ])

This will output both the request being made and the response returned. If the response is JSON encoded, it will pretty-print the JSON, otherwise it will attempt to print out the raw response data.

cro
  • 2,437
  • 2
  • 10
  • 9
-2

MoyaProvider(plugins: [NetworkLoggerPlugin()])

Zontag
  • 147
  • 2
  • 7