在Moya 14中记录响应和请求 [英] Logging response and request in Moya 14
问题描述
有没有办法在Moya 14中记录我的请求和响应而无需使用冗长的内容?
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)
谢谢.
推荐答案
已在在其他地方提供了初始指南Moya的自定义插件,但这是一个详细的示例,将同时显示请求和响应数据.
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.
将以下代码添加到您从何处致电Moya的任何地方:
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)
])
这将同时输出正在发出的请求和返回的响应.如果响应是JSON编码的,它将漂亮地打印JSON,否则将尝试打印出原始响应数据.
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.
这篇关于在Moya 14中记录响应和请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!