Skip to content

Commit

Permalink
Merge pull request #145 from averak/feature/144-static-logger
Browse files Browse the repository at this point in the history
staticなloggerを作成
  • Loading branch information
averak authored Feb 1, 2024
2 parents 7b7a2b6 + 0191af7 commit 504d350
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExcep

@Controller
@RestControllerAdvice
class GlobalRestControllerAdvice(
private val customLogger: Logger,
private val requestScope: RequestScope,
) : ResponseEntityExceptionHandler() {
class GlobalRestControllerAdvice : ResponseEntityExceptionHandler() {

@RequestMapping("/**")
fun handleApiNotFound(): ResponseEntity<Any> {
Expand All @@ -37,7 +34,7 @@ class GlobalRestControllerAdvice(
@ExceptionHandler(ClientAbortException::class)
fun handleException(ex: ClientAbortException) {
// クライアントがリクエストを中断した場合は警告ログを残し、処理を中断する
customLogger.warn(requestScope.getGameContext(), ex)
Logger.warn(ex)
}

@SuppressWarnings("kotlin:S6510")
Expand All @@ -54,12 +51,7 @@ class GlobalRestControllerAdvice(
}

else -> {
try {
this.customLogger.error(requestScope.getGameContext(), e)
} catch (_: HttpMetadataNotFoundException) {
// ゲームコンテキストの取得に失敗する場合でも確実にログを吐く
this.customLogger.error(e)
}
Logger.error(e)
return ResponseEntity(ErrorResponse(e), HttpStatus.INTERNAL_SERVER_ERROR)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import java.time.LocalDateTime
*/
@Component
class AccessLogInterceptor(
private val logger: Logger,
private val requestScope: RequestScope,
) : IRequestInterceptor {

Expand All @@ -25,10 +24,9 @@ class AccessLogInterceptor(

override fun postHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any, modelAndView: ModelAndView?) {
val gctx = requestScope.getGameContext()
logger.info(
gctx,
"access log",
Logger.info(
mapOf(
"message" to "access log",
"http_request" to mapOf(
"client_version" to requestScope.getClientVersion(),
"idempotency_key" to gctx.idempotencyKey.toString(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import java.time.LocalDateTime
@Component
@Order(Int.MAX_VALUE)
class AccessLogInterceptor(
private val logger: Logger,
private val requestScope: RequestScope,
) : ServerInterceptor {

Expand All @@ -23,10 +22,10 @@ class AccessLogInterceptor(
next: ServerCallHandler<ReqT, RespT>,
): ServerCall.Listener<ReqT> {
val begin = LocalDateTime.now()
val logMessage = mutableMapOf<String, Any?>()
logMessage["method"] = call.methodDescriptor.fullMethodName
logMessage["requested_at"] = begin.toString()
logMessage["metadata"] = headers.keys().associateWith {
val requestDetail = mutableMapOf<String, Any?>()
requestDetail["method"] = call.methodDescriptor.fullMethodName
requestDetail["requested_at"] = begin.toString()
requestDetail["metadata"] = headers.keys().associateWith {
headers[Metadata.Key.of(it, Metadata.ASCII_STRING_MARSHALLER)]
}

Expand All @@ -39,11 +38,11 @@ class AccessLogInterceptor(
@Suppress("kotlin:S108")
override fun sendMessage(message: RespT) {
end = LocalDateTime.now()
logMessage["metadata"] = headers.keys().associateWith {
requestDetail["metadata"] = headers.keys().associateWith {
headers[Metadata.Key.of(it, Metadata.ASCII_STRING_MARSHALLER)]
}
if (message is GeneratedMessageV3) {
logMessage["response"] = JsonUtils.decode(
requestDetail["response"] = JsonUtils.decode(
JsonFormat.printer().print(message),
Map::class.java,
)
Expand All @@ -57,16 +56,16 @@ class AccessLogInterceptor(
)
} catch (_: NullPointerException) {
}
logMessage["hint"] = hint
requestDetail["hint"] = hint

logger.info("access log", logMessage)
Logger.info(mapOf("message" to "access log", "request" to requestDetail))
super.sendMessage(message)
}
},
headers,
)
} catch (e: Exception) {
logger.error("access log", e, logMessage)
Logger.error(payload = mapOf("message" to "access log", "request" to requestDetail))
throw Status.INTERNAL.withCause(e).asException()
}
}
Expand Down
117 changes: 48 additions & 69 deletions app/core/src/main/kotlin/net/averak/gsync/core/logger/Logger.kt
Original file line number Diff line number Diff line change
@@ -1,89 +1,68 @@
package net.averak.gsync.core.logger

import net.averak.gsync.core.config.Config
import net.averak.gsync.core.game_context.GameContext
import net.logstash.logback.argument.StructuredArgument
import net.logstash.logback.argument.StructuredArguments
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class Logger(
private val config: Config,
) {
class Logger {

private val logger = LoggerFactory.getLogger(Logger::class.java)

fun info(message: String, payload: Map<String, Any?>) {
this.logger.info(
message,
makeServerInfoPayload(),
StructuredArguments.value("payload", payload),
)
@Autowired
private fun init(config: Config) {
Logger.config = config
}

fun info(gctx: GameContext, message: String, payload: Map<String, Any?>) {
this.logger.info(
message,
makeServerInfoPayload(),
makeGameContextPayload(gctx),
StructuredArguments.value("payload", payload),
)
}
companion object {

fun warn(gctx: GameContext, exception: Exception) {
this.logger.warn(
exception.toString(),
makeServerInfoPayload(),
makeGameContextPayload(gctx),
StructuredArguments.value("exception", exception),
)
}
private lateinit var config: Config

fun error(message: String, exception: Exception, payload: Map<String, Any?>) {
this.logger.error(
message,
makeServerInfoPayload(),
StructuredArguments.value("payload", payload),
StructuredArguments.value("exception", exception),
)
}
private val logger = LoggerFactory.getLogger(Logger::class.java)

fun error(exception: Exception) {
this.logger.error(
exception.toString(),
makeServerInfoPayload(),
StructuredArguments.value("exception", exception),
)
}
fun info(payload: Any? = null) {
val structuredArgs = mutableListOf<StructuredArgument>()
structuredArgs.add(makeServerInfoPayload())
if (payload != null) {
structuredArgs.add(StructuredArguments.value("payload", payload))
}
logger.info("", *structuredArgs.toTypedArray())
}

fun error(gctx: GameContext, exception: Exception) {
this.logger.error(
exception.toString(),
makeServerInfoPayload(),
makeGameContextPayload(gctx),
StructuredArguments.value("exception", exception),
)
}
@Suppress("DuplicatedCode")
fun warn(exception: Exception? = null, payload: Any? = null) {
val structuredArgs = mutableListOf<StructuredArgument>()
structuredArgs.add(makeServerInfoPayload())
if (payload != null) {
structuredArgs.add(StructuredArguments.value("payload", payload))
}
if (exception != null) {
structuredArgs.add(StructuredArguments.value("exception", exception))
}
logger.warn("", *structuredArgs.toTypedArray())
}

private fun makeGameContextPayload(gctx: GameContext): StructuredArgument {
return StructuredArguments.value(
"game_context",
mapOf(
"master_version" to gctx.masterVersion.toString(),
"idempotencyKey" to gctx.idempotencyKey.toString(),
"dateline" to gctx.dateline.toString(),
"currentTime" to gctx.currentTime.toString(),
),
)
}
@Suppress("DuplicatedCode")
fun error(exception: Exception? = null, payload: Any? = null) {
val structuredArgs = mutableListOf<StructuredArgument>()
structuredArgs.add(makeServerInfoPayload())
if (payload != null) {
structuredArgs.add(StructuredArguments.value("payload", payload))
}
if (exception != null) {
structuredArgs.add(StructuredArguments.value("exception", exception))
}
logger.error("", *structuredArgs.toTypedArray())
}

private fun makeServerInfoPayload(): StructuredArgument {
return StructuredArguments.value(
"server",
mapOf(
"version" to config.version,
),
)
private fun makeServerInfoPayload(): StructuredArgument {
return StructuredArguments.value(
"server",
mapOf(
"version" to config.version,
),
)
}
}
}

0 comments on commit 504d350

Please sign in to comment.