Skip to content

Commit

Permalink
Merge branch 'feature/DRAW-240' into sandbox
Browse files Browse the repository at this point in the history
  • Loading branch information
comforest committed Aug 18, 2024
2 parents 9b6513e + 9029613 commit a3c5bf6
Show file tree
Hide file tree
Showing 8 changed files with 49 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class ApiLoggingFilter(
} finally {
logger.info(generateLog(request, response))
response.copyBodyToResponse()
MDC.clear()
}
}

Expand All @@ -45,15 +46,15 @@ class ApiLoggingFilter(
"method" to request.method,
"uri" to request.requestURI,
"query" to request.queryString,
"header" to request.headerNames.asSequence().map { it to request.getHeader(it) }.toMap(),
"header" to request.headerNames.asSequence()
.filterNot { it.lowercase() == "authorization" }
.map { it to request.getHeader(it) }
.toMap(),
"requestBody" to request.contentAsString,

// Response 부분
"status" to response.status,
"responseBody" to String(response.contentAsByteArray),

"requestId" to MDC.get("requestId"),
"userId" to MDC.get("userId"),
)

return objectMapper.writeValueAsString(data)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.xorker.draw.room.RoomRepository
import com.xorker.draw.user.User
import com.xorker.draw.user.UserId
import com.xorker.draw.websocket.message.request.SessionWrapper
import org.slf4j.MDC
import org.springframework.stereotype.Service
import org.springframework.web.socket.WebSocketSession

Expand All @@ -16,9 +17,13 @@ class SessionFactory(
private val roomRepository: RoomRepository,
) {
fun create(session: WebSocketSession, request: SessionInitializeRequest): Session {
val roomId = RoomId(request.roomId?.uppercase() ?: generateRoomId())

MDC.put("roomId", roomId.value)

return SessionWrapper(
session,
RoomId(request.roomId?.uppercase() ?: generateRoomId()),
roomId,
User(getUserId(request.accessToken), request.nickname),
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ package com.xorker.draw.websocket

import com.fasterxml.jackson.databind.ObjectMapper
import com.xorker.draw.exception.InvalidRequestValueException
import com.xorker.draw.exception.UnSupportedException
import com.xorker.draw.mafia.MafiaGameUseCase
import com.xorker.draw.mafia.phase.MafiaPhaseUseCase
import com.xorker.draw.room.RoomId
import com.xorker.draw.user.UserId
import com.xorker.draw.websocket.message.request.RequestAction
import com.xorker.draw.websocket.message.request.dto.WebSocketRequest
import com.xorker.draw.websocket.message.request.dto.game.MafiaGameInferAnswerRequest
import com.xorker.draw.websocket.message.request.dto.game.MafiaGameStartGameRequest
import com.xorker.draw.websocket.message.request.dto.game.MafiaGameVoteMafiaRequest
import org.slf4j.MDC
import org.springframework.stereotype.Component
import org.springframework.web.socket.WebSocketSession

Expand All @@ -24,43 +24,43 @@ class WebSocketRouter(
) {

fun route(session: WebSocketSession, request: WebSocketRequest) {
if (request.action == RequestAction.INIT) {
webSocketController.initializeSession(session, request.extractBody())
return
}

val sessionDto = sessionUseCase.getSession(SessionId(session.id)) ?: throw InvalidRequestValueException
MDC.put("roomId", sessionDto.roomId.value)

when (request.action) {
RequestAction.INIT -> webSocketController.initializeSession(session, request.extractBody())
RequestAction.INIT -> throw UnSupportedException
RequestAction.START_GAME -> {
val requestDto = request.extractBody<MafiaGameStartGameRequest>()

mafiaPhaseUseCase.startGame(RoomId(requestDto.roomId))
mafiaPhaseUseCase.startGame(sessionDto.roomId)
}

RequestAction.DRAW -> mafiaGameUseCase.draw(session.getDto(), request.extractBody())
RequestAction.END_TURN -> mafiaGameUseCase.nextTurnByUser(session.getDto())
RequestAction.DRAW -> mafiaGameUseCase.draw(sessionDto, request.extractBody())
RequestAction.END_TURN -> mafiaGameUseCase.nextTurnByUser(sessionDto)

RequestAction.VOTE -> {
val requestDto = request.extractBody<MafiaGameVoteMafiaRequest>()
val sessionDto = session.getDto()

mafiaGameUseCase.voteMafia(sessionDto, UserId(requestDto.userId))
}

RequestAction.ANSWER -> {
val requestDto = request.extractBody<MafiaGameInferAnswerRequest>()
val sessionDto = session.getDto()

mafiaGameUseCase.inferAnswer(sessionDto, requestDto.answer)
}

RequestAction.DECIDE_ANSWER -> {
val requestDto = request.extractBody<MafiaGameInferAnswerRequest>()
val sessionDto = session.getDto()

mafiaGameUseCase.decideAnswer(sessionDto, requestDto.answer)
}
}
}

private fun WebSocketSession.getDto(): Session =
sessionUseCase.getSession(SessionId(this.id)) ?: throw InvalidRequestValueException

private inline fun <reified T : Any> WebSocketRequest.extractBody(): T {
return objectMapper.readValue(this.body, T::class.java)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import com.xorker.draw.support.logging.defaultApiJsonMap
import com.xorker.draw.support.logging.logger
import com.xorker.draw.support.logging.registerRequestId
import com.xorker.draw.websocket.SessionId
import com.xorker.draw.websocket.SessionInitializeRequest
import com.xorker.draw.websocket.SessionUseCase
import com.xorker.draw.websocket.message.request.RequestAction
import com.xorker.draw.websocket.message.request.dto.WebSocketRequest
import org.slf4j.MDC
import org.springframework.stereotype.Component
import org.springframework.web.socket.CloseStatus
import org.springframework.web.socket.WebSocketSession
Expand All @@ -31,18 +34,26 @@ class WebSocketLogger(

fun handleRequest(session: WebSocketSession, request: WebSocketRequest, origin: (WebSocketSession, WebSocketRequest) -> Unit) {
registerRequestId()

try {
origin(session, request)
} finally {
val log = generateLog(SessionId(session.id), request)
logger.info(log)
MDC.clear()
}
}

private fun generateLog(sessionId: SessionId, request: WebSocketRequest): String {
val body: Any? = if (request.action == RequestAction.INIT) {
objectMapper.readValue(request.body, SessionInitializeRequest::class.java).copy(accessToken = "[masked]")
} else {
request.body
}

val data = defaultApiJsonMap(
"action" to request.action,
"requestBody" to request.body,
"requestBody" to body,
"sessionId" to sessionId.value,
)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package com.xorker.draw.websocket.message.request.dto.game

data class MafiaGameStartGameRequest(
val roomId: String,
val roomId: String?,
)
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.xorker.draw.support.logging

import java.time.LocalDateTime
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID
import org.slf4j.Logger
Expand All @@ -15,11 +15,13 @@ fun registerRequestId() {

private val TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
fun defaultApiJsonMap(vararg pairs: Pair<String, Any?>): MutableMap<String, Any?> {
val now = LocalDateTime.now()
val now = ZonedDateTime.now()

val map = mutableMapOf(*pairs)

map["timestamp"] = TIMESTAMP_FORMATTER.format(now)
map["requestId"] = MDC.get("requestId")
map["userId"] = MDC.get("userId")

return map
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ class XorkerJsonLayout : JsonLayout() {

companion object {
// MDC에서 Json에 넣을 목록
private val MDC_LIST = listOf("requestId", "userId")
private val MDC_LIST = listOf("requestId", "userId", "roomId")
}
}
12 changes: 6 additions & 6 deletions support/logging/src/main/resources/logback-appender.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
</appender>

<appender name="CONSOLE_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/console/${HOSTNAME}.log</file>
<file>${LOG_PATH}/console/${HOSTNAME}-console.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/console/${HOSTNAME}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<fileNamePattern>${LOG_PATH}/console/${HOSTNAME}-console-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
<maxFileSize>20MB</maxFileSize>
<maxHistory>7</maxHistory>
<totalSizeCap>100MB</totalSizeCap>
Expand All @@ -37,9 +37,9 @@
</appender>

<appender name="API_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/api/${HOSTNAME}.log</file>
<file>${LOG_PATH}/api/${HOSTNAME}-api.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/api/${HOSTNAME}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<fileNamePattern>${LOG_PATH}/api/${HOSTNAME}-api-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
<maxFileSize>20MB</maxFileSize>
<maxHistory>7</maxHistory>
<totalSizeCap>100MB</totalSizeCap>
Expand All @@ -50,9 +50,9 @@
</appender>

<appender name="WS_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/ws.log</file>
<file>${LOG_PATH}/ws/${HOSTNAME}-ws.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/ws/${HOSTNAME}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<fileNamePattern>${LOG_PATH}/ws/${HOSTNAME}-ws-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
<maxFileSize>20MB</maxFileSize>
<maxHistory>7</maxHistory>
<totalSizeCap>100MB</totalSizeCap>
Expand Down

0 comments on commit a3c5bf6

Please sign in to comment.