Skip to content

Commit

Permalink
chore: Exception 발생 시 상세한 Logging
Browse files Browse the repository at this point in the history
  • Loading branch information
kkanggu committed Aug 18, 2023
1 parent c7256ed commit c0890d3
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,68 +24,74 @@ class RequestLoggingFilter : OncePerRequestFilter() {
return
}

request.setAttribute("isLogged", false)

val wrappedRequest = ContentCachingRequestWrapper(request)
val wrappedResponse = ContentCachingResponseWrapper(response)

filterChain.doFilter(wrappedRequest, wrappedResponse)

val requestInfo = makeRequestInfo(wrappedRequest)
val responseInfo = makeResponseInfo(wrappedResponse)
if (!(request.getAttribute("isLogged") as Boolean)) {
val requestInfo = makeRequestInfo(wrappedRequest)
val responseInfo = makeResponseInfo(wrappedResponse)

log.info {
"""
{
"request" : $requestInfo,
"response" : $responseInfo
log.info {
"""
{
"request" : $requestInfo,
"response" : $responseInfo
}
""".trimIndent()
}
""".trimIndent()
}
}

fun makeRequestInfo(request: ContentCachingRequestWrapper): String {
val requestHeaders = request.headerNames.toList().associateWith {
request.getHeader(it)
}
val requestBody = getBody(request.contentAsByteArray)
companion object {
fun makeRequestInfo(request: ContentCachingRequestWrapper): String {
val requestHeaders = request.headerNames.toList().associateWith {
request.getHeader(it)
}
val requestBody = getBody(request.contentAsByteArray)

return """
return """
{
"client ip" : "${request.remoteAddr}",
"uri" : "${request.requestURI}",
"headers" : ${jacksonObjectMapper().writeValueAsString(requestHeaders)},
"body" : $requestBody
}
""".trimIndent()
}

fun makeResponseInfo(response: ContentCachingResponseWrapper): String {
val responseHeaders = response.headerNames.toList().associateWith {
response.getHeader(it)
}
val responseBody = getBody(response.contentAsByteArray)
response.copyBodyToResponse()

return """
fun makeResponseInfo(response: ContentCachingResponseWrapper): String {
val responseHeaders = response.headerNames.toList().associateWith {
response.getHeader(it)
}
val responseBody = getBody(response.contentAsByteArray)
response.copyBodyToResponse()

return """
{
"status" : "${response.status}",
"headers" : ${jacksonObjectMapper().writeValueAsString(responseHeaders)},
"body" : $responseBody
}
""".trimIndent()
}

private fun getBody(body: ByteArray): String {
if (body.isEmpty()) {
return "{}"
}

val readTree = jacksonObjectMapper().readTree(body)
val filteredJson: ObjectNode = jacksonObjectMapper().createObjectNode()
private fun getBody(body: ByteArray): String {
if (body.isEmpty()) {
return "{}"
}

readTree.fields().forEach { (key, value) ->
filteredJson.set<JsonNode>(key, value)
}
val readTree = jacksonObjectMapper().readTree(body)
val filteredJson: ObjectNode = jacksonObjectMapper().createObjectNode()

return jacksonObjectMapper().writeValueAsString(filteredJson)
readTree.fields().forEach { (key, value) ->
filteredJson.set<JsonNode>(key, value)
}

return jacksonObjectMapper().writeValueAsString(filteredJson)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,35 +1,61 @@
package com.example.daitssuapi.common.exception

import com.example.daitssuapi.common.configuration.RequestLoggingFilter
import com.example.daitssuapi.common.dto.Response
import jakarta.servlet.http.HttpServletRequest
import mu.KLogger
import mu.KotlinLogging
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.util.ContentCachingRequestWrapper

@RestControllerAdvice
class ExceptionHandler() {
private val log: KLogger = KotlinLogging.logger {}

@ExceptionHandler(Exception::class)
fun handleException(exception: Exception): ResponseEntity<Response<Any>> {
fun handleException(exception: Exception, request: HttpServletRequest): ResponseEntity<Response<Any>> {
val requestInfo = RequestLoggingFilter.makeRequestInfo(ContentCachingRequestWrapper(request))

lateinit var response: Response<Any>
var httpStatus: HttpStatus = HttpStatus.INTERNAL_SERVER_ERROR

when (exception) {
is BaseException -> {
response = Response(code = exception.errorCode.code, message = exception.errorCode.message, data = null)
httpStatus = exception.httpStatus
log.warn("${exception.errorCode} + $httpStatus")

log.warn {
"""
{
"request" : $requestInfo,
"code" : "${exception.errorCode}",
"message" : "${exception.errorCode.message}",
"status" : "$httpStatus"
}
""".trimIndent()
}
}

else -> {
response = Response(code = 1, message = "", data = null)
log.error("${exception.message}")

log.warn {
"""
{
"request" : $requestInfo,
"message" : "${exception.message?.replace("\"", "'")}",
"status" : "$httpStatus"
}
""".trimIndent()
}
}
}

request.setAttribute("isLogged", true)

return ResponseEntity.status(httpStatus).body(response)
}
}

0 comments on commit c0890d3

Please sign in to comment.