|
| 1 | +package io.github.mfaisalkhatri.api.logger; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.microsoft.playwright.APIResponse; |
| 6 | +import org.apache.commons.lang3.StringUtils; |
| 7 | +import org.apache.logging.log4j.LogManager; |
| 8 | + |
| 9 | + |
| 10 | +public class Logger { |
| 11 | + |
| 12 | + private final APIResponse response; |
| 13 | + private final org.apache.logging.log4j.Logger log; |
| 14 | + |
| 15 | + public Logger (final APIResponse response) { |
| 16 | + this.response = response; |
| 17 | + this.log = LogManager.getLogger (getClass ()); |
| 18 | + } |
| 19 | + |
| 20 | + public void logResponseDetails () { |
| 21 | + String responseBody = this.response.text (); |
| 22 | + this.log.info ("Logging Response Details....\n responseHeaders: {}, \nstatusCode: {},", |
| 23 | + this.response.headers (), this.response.status ()); |
| 24 | + this.log.info ("\n Response body: {}", prettyPrintJson (responseBody)); |
| 25 | + this.log.info ("End of Logs!"); |
| 26 | + } |
| 27 | + |
| 28 | + private String prettyPrintJson (final String text) { |
| 29 | + if (StringUtils.isNotBlank (text) && StringUtils.isNotEmpty (text)) { |
| 30 | + try { |
| 31 | + final ObjectMapper objectMapper = new ObjectMapper (); |
| 32 | + final Object jsonObject = objectMapper.readValue (text, Object.class); |
| 33 | + return objectMapper.writerWithDefaultPrettyPrinter () |
| 34 | + .writeValueAsString (jsonObject); |
| 35 | + } catch (final JsonProcessingException e) { |
| 36 | + this.log.error ("Failed to pretty print JSON: {}", e.getMessage (), e); |
| 37 | + } |
| 38 | + } |
| 39 | + return "No response body found!"; |
| 40 | + |
| 41 | + } |
| 42 | +} |
| 43 | + |
0 commit comments