Swift Byte #8: How to Use Alamofire 5 Event Monitor to log request & responses
A cleaner approach to log Alamofire 5 requests and responses
While I was working on refactoring the networking layer and upgrading Alamofire from 4 to 5, I learn about the existence of EventMonitor
.
What is EventMonitor
?
Essentially, EventMonitor
is a protocol that allows me to "monitor” the session’s network requests and response.
Implementing EventMonitor
is a matter of creating a class that conforms to the EventMonitor
protocol.
For example, in my case I want to log every request and response that’s happening to Xcode console log to make debugging easier.
/// Monitor Alamofire request and response and print it to Xcode console
/// for debugging purpose.
class ConsoleLogEventMonitor: EventMonitor {
func requestDidResume(_ request: Request) {
print("""
[REQ]: \(request.request?.url?.absoluteString ?? "")
\(request.cURLDescription())
""")
}
func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value, AFError>) {
print("""
[RESP]: \(request.request?.url?.absoluteString ?? "")
\(response.debugDescription)
""")
}
}
To use it, I just have to add ConsoleLogEventMonitor
to the Alamofire’s Session
like so:
let session = Session(eventMonitors: [ConsoleLogEventMonitor()])
session.request(urlComponents)
With this, each of my session requests will be printed out in the Xcode console.
Session
can accept multiple event monitors too. In a way, I can create multiple event monitors based on functionalities like DataDog analytics, logging or even custom behaviours.
That’s all for from me today. Thanks for reading!