개발 이모저모

HTTP 통신 로그 이쁘장하게 찍어보기

c0de_h0ng 2021. 11. 16. 21:59
728x90

Retrofit2를 개발할 때 OkHttp3을 이용하여 HTTP 통신에 타임아웃, 쿠키, 로그 등 옵션을 설정할 수 있다. 여기서 로그 옵션을 설정하게 되면 HTTP 통신 요청과 응답 값을 로그를 통해서 알 수 있다. 하지만 로그에서는 pretty하게 프린트되지 않아서 가독성이 떨어진다. 이러한 로그를 pretty하게 출력되도록 하는 방법이 있다.

HTTP 통신 로그 pretty하게 찍는 방법

HTTP 통신 로그를 pretty하게 찍기 위해서는 HttpLoggingInterceptor에 인자로 커스텀 클래스(CustomHttpLogging)를 넘겨야 한다.

val interceptor = HttpLoggingInterceptor(CustomHttpLogging())
class CustomHttpLogging : HttpLoggingInterceptor.Logger {

    override fun log(message: String) {
        val logName = "OkHttp"
        if (!message.startsWith("{")) {
            Log.d(logName, message)
            return
        }
        try {
            val prettyPrintJson = GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(JsonParser.parseString(message))
            Log.d(logName, prettyPrintJson)
        } catch (e: JsonSyntaxException) {
            Log.d(logName, message)
        }
    }

}

위와 같이 interceptor 커스텀 클래스를 생성하면 된다. logName 같은 경우는 원하는 TAG 이름을 사용해도 된다.