How to Create a Custom HttpClient Logger (2024)
A custom `IHttpClientLogger` can replace verbose default HTTP client logs with focused request, response, and failure information.
Transcript 1 topic
Custom HTTP logger
0:00Have you ever looked at the output of an HTTP client logger? Like me, it's pretty wordy. But we can make it better. Let's create a custom logger that we can use to report just the information we're interested in. Any HTTP client logger has to implement the I http client logger interface.
So let's do it. This class implements that interface and has a private I logger that we're gonna use to show up what we can do. Now the I http client logger interface exposes three methods. Log request start, log request stop and log request failed. Let's start with log request start.
This method has one parameter that's saying HTTP request message and it's pretty straightforward. We're just gonna log some information that's a little more brief than the default logger. And since there's nothing really fancy about it, let's go ahead and move on to the log request stop and log request failed methods. In both instances, can see we're just logging something out very simply to show us the different places that we're hitting in our code as an example. Now that it's ready to go, we can use an HTTP client factory to register our logger, in place of the default one.
As a quick review, we're gonna first remove all existing loggers. That is mainly the default one. And that's just so that we don't clutter up our log with what comes out of the default logger and what's coming out of ours. And then finally, we add our logger to the HTTP client factory. Just like that, we've got our custom HTTP client logger set up and ready to go.
I'm curious though, do you use custom HTTP client loggers? Let me know in the comments below if you do and if this video helped. Until next time.
Sign in to join in. Reading needs nothing.