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 이름을 사용해도 된다.
'개발 이모저모' 카테고리의 다른 글
시작일부터 종료일 표현해보기 (0) | 2022.12.15 |
---|---|
카카오 주소 및 키워드 api를 활용한 주소 검색 서비스 제작 (0) | 2021.11.16 |
지도에 중복 위경도 마커를 찍어보자 (0) | 2021.11.16 |
SharedPreference를 이용한 최근 검색어 리스트 만들기 (0) | 2021.11.16 |
흔들어봐! 새로운 화면이 열릴꺼야~ (0) | 2021.11.16 |