1

I have a library that perform http requests to a series of external APIs. This library is a SDK that every other projects can import to use inside.

I am adding a lot of logs inside my library and, in some steps, I would like to log the HttpRequest and HttpResponse from external call. I have tried to log java.net.HttpRequest that was build using HttpRequest.builder() using jackson but I got an empty JSON.

As example, I'll show my code:


   fun getFacebookUser(identifier: String): HttpResponse {
        val mapper = ObjectMapper()
        logger.debug("starting recover a user...")
        val httpRequest = buildHttpRequest(...) // internal function that returns a HttpRequest
        logger.debug("request coming:", httpRequest) // how to log httpRequest as json?
        ....more code....
    }

I really want to avoid something like:

fun myAwesomeLogFunction(request: HttpRequest) {
    logger.debug("request uri", request.uri())
    //and goes  on for every attribute that I want to log
}

Is there any way to log entire httpRequest as json?

edit: HttpClient, HttpRequest and all Http stuff comes from java.net.http

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • Don't we need to know what HTTP library you're using to know what format the request is in? – Tenfour04 Jun 11 '20 at 13:19
  • Is it strictly Json that you need, or that you just want to log all the parameters of the request without having to know which specific attributes it uses? – Tenfour04 Jun 11 '20 at 13:37

2 Answers2

1

Try using this way

    JSONObject json = Util.parseJson(httpRequest);
    logger.debug("Response data", json.toString());
BALAJI V S
  • 63
  • 6
1

One possible way is implementing the builder class(which could considered as hard-way, but works), and keep all required data somewhere, to make them as JSON.

E.g.

class Loggable_HttpRequest_Builder implements HttpRequest.Builder{
//get an actual builder
private HttpRequest.Builder actual_builder = HttpRequest.newBuilder();
//map for keeping data for building json at the end
private Map<String,String> json_data=...
@Override
public HttpRequest.Builder header(String name, String value) {
// log the name + value
json_data.put(name,value);
//call the actual builder
actual_builder.header(name,value);
}
/*
implement all required funcs, simply log the request, and call the same method of actual_builder, e.g. as above
*/
public String get_json_log(){
/*JSON-ize the json_data, and return*/
}
}

(sorry for java stuff, kotlin is so sweet for me)