Skip to content

Commit

Permalink
feat: change logging interceptor to filter to wrap request
Browse files Browse the repository at this point in the history
  • Loading branch information
minjun3021 committed Oct 3, 2023
1 parent f9e54c0 commit 35e9d24
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 52 deletions.
14 changes: 10 additions & 4 deletions src/main/kotlin/com/group4/ticketingservice/config/WebConfig.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package com.group4.ticketingservice.config

import com.google.gson.Gson
import com.group4.ticketingservice.utils.logging.LogInterceptor
import com.group4.ticketingservice.filter.LogFilter
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.converter.json.GsonHttpMessageConverter
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

@Configuration
Expand All @@ -15,7 +16,12 @@ class WebConfig(private val gson: Gson) : WebMvcConfigurer {
gsonHttpMessageConverter.gson = gson
converters.add(gsonHttpMessageConverter)
}
override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(LogInterceptor())

@Bean
fun loggingFilter(): FilterRegistrationBean<LogFilter> {
val registrationBean: FilterRegistrationBean<LogFilter> = FilterRegistrationBean<LogFilter>()
registrationBean.setFilter(LogFilter())
registrationBean.addUrlPatterns("/*")
return registrationBean
}
}
58 changes: 58 additions & 0 deletions src/main/kotlin/com/group4/ticketingservice/filter/LogFilter.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.group4.ticketingservice.filter

import com.group4.ticketingservice.utils.logging.logger
import jakarta.servlet.Filter
import jakarta.servlet.FilterChain
import jakarta.servlet.ServletRequest
import jakarta.servlet.ServletResponse
import jakarta.servlet.http.HttpServletRequest
import org.slf4j.MDC
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.util.ContentCachingRequestWrapper
import java.net.URLEncoder
import java.util.UUID

class LogFilter : Filter {

private val log = logger()

override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
val httpServletRequest = ContentCachingRequestWrapper(request as HttpServletRequest)

MDC.put("requestId", UUID.randomUUID().toString())

val queryParams = getQueryParams(request)
val requestInfo = "[${request.method}] ${request.requestURI}$queryParams"

log.info("{} userId : {}", requestInfo, getUserId())

chain.doFilter(httpServletRequest, response)

var reqContent = String(httpServletRequest.contentAsByteArray)
reqContent = reqContent.replace("\n", "").replace("\r", "")

if (reqContent != "") {
reqContent = "RequestBody : $reqContent"
log.info("{}", reqContent)
}
MDC.remove("requestId")
}

private fun getUserId() = SecurityContextHolder.getContext().authentication.principal.toString()

private fun getQueryParams(request: HttpServletRequest): String {
val paramMap = request.parameterMap
val params = StringBuilder()
if (paramMap.isNotEmpty()) params.append("?")
for ((key, value1) in paramMap) {
if (params.isNotEmpty()) params.append("&")
for (value in value1) {
params.append(URLEncoder.encode(key, "UTF-8"))
params.append("=")
params.append(URLEncoder.encode(value, "UTF-8"))
}
}

return params.toString()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class GlobalExceptionHandler {
message = exception.javaClass.name,
path = request.requestURI
)
log.warn(exception.message)
log.error(exception.toString(), exception)
return ResponseEntity(errorDto, errorCode.status)
}

Expand Down

This file was deleted.

2 changes: 2 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ management.endpoints.web.exposure.include=prometheus

spring.mvc.log-resolved-exception=false



#ticketing.jwt.secret=d2VhcmVuYXZ5c3dkZXZlbG9wZXJzLmFuZGlhbW1pbmp1bjMwMjE=
#The JWT specification requires HMAC keys to be >= 256 bits long.
#ticketing.jwt.expiration-hours=24
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/logback-spring.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">

<encoder>
<pattern>%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p){green} %clr(${PID}){magenta} --- %clr([%t]){faint} %clr(%-40.40logger{39}){cyan} [%clr(%X{requestId}){red}, %clr(%X{userId}){yellow}] : %m%n</pattern>
<pattern>%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p){green} %clr(${PID}){magenta} --- %clr([%t]){faint} %clr(%-40.40logger{39}){cyan} [%clr(%X{requestId}){red}] : %m%n</pattern>

</encoder>
</appender>
Expand Down

0 comments on commit 35e9d24

Please sign in to comment.