Events allow you to capture metrics on your application’s HTTP calls. Use events to monitor:
- The size and frequency of the HTTP calls your application makes. If you’re making too many calls, or your calls are too large, you should know about it!
- The performance of these calls on the underlying network. If the network’s performance isn’t sufficient, you need to either improve the network or use less of it.
Subclass EventListener and override methods for the events you are interested in. In a successful HTTP call with no redirects or retries the sequence of events is described by this flow.
Here’s a sample event listener that prints each event with a timestamp.
We make a couple calls:
And the listener prints the corresponding events:
Notice how no connect events are fired for the second call. It reused the connection from the first request for dramatically better performance.
In the preceding example we used a field,
callStartNanos, to track the elapsed time of each event. This is handy, but it won’t work if multiple calls are executing concurrently. To accommodate this, use a
Factory to create a new
EventListener instance for each
Call. This allows each listener to keep call-specific state.
This sample factory creates a unique ID for each call and uses that ID to differentiate calls in log messages.
We can use this listener to race a pair of concurrent HTTP requests:
Running this race over home WiFi shows the Times (
0002) completes just slightly sooner than the Post (
EventListener.Factory also makes it possible to limit metrics to a subset of calls. This one captures metrics on a random 10%:
When an operation fails, a failure method is called. This is connectFailed() for failures while building a connection to the server, and callFailed() when the HTTP call fails permanently. When a failure happens it is possible that a start event won’t have a corresponding end event.
OkHttp is resilient and can automatically recover from some connectivity failures. In this case, the
connectFailed() event is not terminal and not followed by
callFailed(). Event listeners will receive multiple events of the same type when retries are attempted.
A single HTTP call may require follow-up requests to be made to handle authentication challenges, redirects, and HTTP-layer timeouts. In such cases multiple connections, requests, and responses may be attempted. Follow-ups are another reason a single call may trigger multiple events of the same type.
Events is available as a public API in OkHttp 3.11. Future releases may introduce new event types; you will need to override the corresponding methods to handle them.