Skip to content

Commit

Permalink
✨: apply global KLogger #18 (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
daehwan2da authored Mar 2, 2024
1 parent 09ed7e6 commit e96cb14
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 46 deletions.
2 changes: 2 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@ subprojects {
compileOnly("org.projectlombok:lombok")
annotationProcessor("org.projectlombok:lombok")

// kotlin
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("io.github.oshai:kotlin-logging-jvm:5.1.0")

testImplementation("org.springframework.boot:spring-boot-starter-test")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.th.plu.api.service.auth.jwt

import com.th.plu.api.service.redis.RedisHandler
import com.th.plu.common.Slf4JKotlinLogging.log
import com.th.plu.common.constant.JwtKey
import com.th.plu.common.constant.RedisKey
import com.th.plu.common.exception.code.ErrorCode
Expand All @@ -10,7 +11,6 @@ import io.jsonwebtoken.io.Decoders
import io.jsonwebtoken.io.DecodingException
import io.jsonwebtoken.security.Keys
import jakarta.annotation.PostConstruct
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import java.security.Key
Expand All @@ -23,7 +23,6 @@ class JwtHandler(
@Value("\${jwt.secret}")
private var jwtSecret: String? = null
private var secretKey: Key? = null
private val log = LoggerFactory.getLogger(this.javaClass)

companion object {
// private const val ACCESS_TOKEN_EXPIRE_TIME = 10 * 60 * 1000L // 10λΆ„
Expand Down Expand Up @@ -71,19 +70,19 @@ class JwtHandler(
Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token)
return true
} catch (e: SecurityException) {
log.warn("Invalid JWT Token", e)
log.warn(e) { "Invalid JWT Token" }
} catch (e: MalformedJwtException) {
log.warn("Invalid JWT Token", e)
log.warn(e) { "Invalid JWT Token" }
} catch (e: DecodingException) {
log.warn("Invalid JWT Token", e)
log.warn(e) { "Invalid JWT Token" }
} catch (e: ExpiredJwtException) {
log.warn("Expired JWT Token", e)
log.warn(e) { "Expired JWT Token" }
} catch (e: UnsupportedJwtException) {
log.warn("Unsupported JWT Token", e)
log.warn(e) { "Unsupported JWT Token" }
} catch (e: IllegalArgumentException) {
log.warn("JWT claims string is empty.", e)
log.warn(e) { "JWT claims string is empty." }
} catch (e: Exception) {
log.error("Unhandled JWT exception", e)
log.error(e) { "Unhandled JWT exception" }
}
return false
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.th.plu.common

import io.github.oshai.kotlinlogging.KLogger
import io.github.oshai.kotlinlogging.KotlinLogging

object Slf4JKotlinLogging {
val <reified T> T.log: KLogger
inline get() = KotlinLogging.logger {}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.th.plu.common.aop.advice

import com.fasterxml.jackson.databind.exc.InvalidFormatException
import com.th.plu.common.Slf4JKotlinLogging.log
import com.th.plu.common.dto.response.ApiResponse
import com.th.plu.common.exception.code.ErrorCode
import com.th.plu.common.exception.model.*
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.validation.BindException
Expand All @@ -20,22 +20,20 @@ import org.springframework.web.servlet.resource.NoResourceFoundException

@RestControllerAdvice
class ExceptionControllerAdvice {
private val log = LoggerFactory.getLogger(this.javaClass)

/**
* 400 Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException::class)
fun handleValidationException(exception: ValidationException): ApiResponse<Any> {
log.error(exception.message)
log.error(exception) { exception.message }
return ApiResponse.error(exception.errorCode)
}

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleMethodArgumentNotValidException(exception: MethodArgumentNotValidException): ApiResponse<Any> {
log.error(exception.message, exception);
log.error(exception) { exception.message }
return ApiResponse.error(
ErrorCode.METHOD_ARGUMENT_NOT_VALID_EXCEPTION,
exception.bindingResult.fieldError?.defaultMessage.toString()
Expand All @@ -45,7 +43,7 @@ class ExceptionControllerAdvice {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException::class)
fun handleBindException(exception: BindException): ApiResponse<Any> {
log.error(exception.message, exception);
log.error(exception) { exception.message }
return ApiResponse.error(
ErrorCode.BIND_EXCEPTION,
exception.bindingResult.fieldError?.defaultMessage.toString()
Expand All @@ -61,7 +59,7 @@ class ExceptionControllerAdvice {
]
)
fun handleInvalidFormatException(exception: Exception): ApiResponse<Any> {
log.error(exception.message, exception);
log.error(exception) { exception.message }
return ApiResponse.error(ErrorCode.INVALID_FORMAT_EXCEPTION);
}

Expand All @@ -71,7 +69,7 @@ class ExceptionControllerAdvice {
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(UnauthorizedException::class)
fun handleUnauthorizedException(exception: UnauthorizedException): ApiResponse<Any> {
log.error(exception.message, exception)
log.error(exception) { exception.message }
return ApiResponse.error(exception.errorCode)
}

Expand All @@ -81,7 +79,7 @@ class ExceptionControllerAdvice {
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(ForbiddenException::class)
fun handleForbiddenException(exception: ForbiddenException): ApiResponse<Any> {
log.error(exception.message, exception)
log.error(exception) { exception.message }
return ApiResponse.error(exception.errorCode)
}

Expand All @@ -91,7 +89,7 @@ class ExceptionControllerAdvice {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NotFoundException::class)
fun handleNotFoundException(exception: NotFoundException): ApiResponse<Any> {
log.error(exception.message, exception)
log.error(exception) { exception.message }
return ApiResponse.error(exception.errorCode)
}

Expand All @@ -102,7 +100,7 @@ class ExceptionControllerAdvice {
NoResourceFoundException::class]
)
fun handleNotFoundEndpointException(exception: Exception): ApiResponse<Any> {
log.error(exception.message, exception)
log.error(exception) { exception.message }
return ApiResponse.error(ErrorCode.NOT_FOUND_ENDPOINT_EXCEPTION)
}

Expand All @@ -121,7 +119,7 @@ class ExceptionControllerAdvice {
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(ConflictException::class)
fun handleConflictException(exception: ConflictException): ApiResponse<Any> {
log.error(exception.message, exception)
log.error(exception) { exception.message }
return ApiResponse.error(exception.errorCode)
}

Expand All @@ -140,7 +138,7 @@ class ExceptionControllerAdvice {
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception::class)
fun handleInternalServerException(exception: Exception): ApiResponse<Any> {
log.error(exception.message, exception)
log.error(exception) { exception.message }
return ApiResponse.error(ErrorCode.INTERNAL_SERVER_EXCEPTION)
}

Expand All @@ -150,7 +148,7 @@ class ExceptionControllerAdvice {
@ResponseStatus(HttpStatus.BAD_GATEWAY)
@ExceptionHandler(BadGatewayException::class)
fun handleBadGatewayException(exception: BadGatewayException): ApiResponse<Any> {
log.error(exception.message, exception)
log.error(exception) { exception.message }
return ApiResponse.error(exception.errorCode)
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package com.th.plu.external.client.firebase

import com.th.plu.common.Slf4JKotlinLogging.log
import com.th.plu.common.exception.code.ErrorCode
import com.th.plu.common.exception.model.BadGatewayException
import com.th.plu.common.exception.model.ValidationException
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatusCode
import org.springframework.http.MediaType
Expand All @@ -19,7 +18,6 @@ class WebClientFirebaseApiCaller(private val webClient: WebClient) : FirebaseApi
@Value("\${spring.cloud.firebase.message.uri}")
private var messageApiUri: String? = null

private val log = LoggerFactory.getLogger(this.javaClass)
private val LOG_PREFIX = "====> [Firebase Messaging]"


Expand All @@ -33,19 +31,25 @@ class WebClientFirebaseApiCaller(private val webClient: WebClient) : FirebaseApi
.body(BodyInserters.fromValue<String>(message))
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError) {
Mono.error(BadGatewayException(ErrorCode.BAD_GATEWAY_EXCEPTION,
createFirebaseFailMessage(it, message)
))
Mono.error(
BadGatewayException(
ErrorCode.BAD_GATEWAY_EXCEPTION,
createFirebaseFailMessage(it, message)
)
)
}
.onStatus(HttpStatusCode::is5xxServerError) {
Mono.error(BadGatewayException(ErrorCode.BAD_GATEWAY_EXCEPTION,
createFirebaseFailMessage(it, message)
))
Mono.error(
BadGatewayException(
ErrorCode.BAD_GATEWAY_EXCEPTION,
createFirebaseFailMessage(it, message)
)
)
}
.toBodilessEntity()
.subscribe {
if (it.statusCode.is2xxSuccessful) {
log.info("${LOG_PREFIX}\nStatus: ${it.statusCode}\nMessage: ${message}")
log.info { "${LOG_PREFIX}\nStatus: ${it.statusCode}\nMessage: ${message}" }
} else {
throw BadGatewayException(
ErrorCode.BAD_GATEWAY_EXCEPTION,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.th.plu.external.sqs.sender

import com.fasterxml.jackson.databind.ObjectMapper
import com.th.plu.common.Slf4JKotlinLogging.log
import com.th.plu.external.sqs.dto.FirebaseMessageDto
import io.awspring.cloud.sqs.operations.SendResult
import io.awspring.cloud.sqs.operations.SqsTemplate
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import java.util.*
Expand All @@ -15,13 +15,12 @@ class SqsSenderImpl(private val objectMapper: ObjectMapper, private val sqsTempl
@Value("\${spring.cloud.aws.sqs.queue.name}")
private var queueName: String? = null

private val log = LoggerFactory.getLogger(this.javaClass)
private val LOG_PREFIX = "====> [SQS_SENDER]"
private val GROUP_ID = "plu-sqs"
private val MESSAGE_TYPE_HEADER = "type"

override fun sendFirebaseMessage(message: FirebaseMessageDto): SendResult<String> {
log.info("${LOG_PREFIX} send Message(type: ${message.type})")
log.info { "$LOG_PREFIX send Message(type: ${message.type})" }
return sqsTemplate.send {
it.queue(queueName.toString())
it.header(MESSAGE_TYPE_HEADER, message.type.name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ package com.th.plu.notification.firebase

import com.fasterxml.jackson.databind.ObjectMapper
import com.google.auth.oauth2.GoogleCredentials
import com.th.plu.common.Slf4JKotlinLogging.log
import com.th.plu.common.exception.code.ErrorCode
import com.th.plu.common.exception.model.BadGatewayException
import com.th.plu.external.client.firebase.FirebaseApiCaller
import com.th.plu.notification.firebase.dto.FcmMessageRequest
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.io.ClassPathResource
import org.springframework.stereotype.Service
Expand All @@ -22,7 +22,6 @@ class FirebaseCloudMessageService(
@Value("\${spring.cloud.firebase.auth.uri}")
private var firebaseAuthUri: String? = null

private val log = LoggerFactory.getLogger(this.javaClass)
private val LOG_PREFIX = "====> [Firebase Cloud Message]"

fun sendMessageTo(fcmToken: String?, title: String, body: String) {
Expand All @@ -46,10 +45,10 @@ class FirebaseCloudMessageService(

return googleCredentials.accessToken.tokenValue
} catch (exception: Exception) {
log.error(exception.message, exception)
log.error(exception) { exception.message }
throw BadGatewayException(
ErrorCode.BAD_GATEWAY_EXCEPTION,
"${LOG_PREFIX} FCM Access Token λ°œκΈ‰ κ³Όμ •μ—μ„œ μ—λŸ¬κ°€ λ°œμƒν•˜μ˜€μŠ΅λ‹ˆλ‹€."
"$LOG_PREFIX FCM Access Token λ°œκΈ‰ κ³Όμ •μ—μ„œ μ—λŸ¬κ°€ λ°œμƒν•˜μ˜€μŠ΅λ‹ˆλ‹€."
)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package com.th.plu.notification.sqs

import com.fasterxml.jackson.databind.ObjectMapper
import com.th.plu.common.Slf4JKotlinLogging.log
import com.th.plu.common.exception.code.ErrorCode
import com.th.plu.common.exception.model.InternalServerException
import com.th.plu.external.sqs.dto.FirebaseMessageDto
import com.th.plu.external.sqs.dto.MessageType
import com.th.plu.notification.firebase.FirebaseCloudMessageService
import io.awspring.cloud.sqs.annotation.SqsListener
import org.slf4j.LoggerFactory
import org.springframework.messaging.handler.annotation.Headers
import org.springframework.messaging.handler.annotation.Payload
import org.springframework.stereotype.Service
Expand All @@ -17,25 +17,32 @@ class SqsConsumer(
private val objectMapper: ObjectMapper,
private val FirebaseCloudMessageService: FirebaseCloudMessageService
) {
private val log = LoggerFactory.getLogger(this.javaClass)
private val LOG_PREFIX = "====> [SQS Queue Request]";

private val MESSAGE_TYPE_HEADER = "type"

@SqsListener("pluNotification.fifo")
fun consume(@Payload info: String, @Headers headers: Map<String, String>) {
try {
log.info("${LOG_PREFIX}\ninfo: ${info}\nheaders: ${headers}")
log.info { "$LOG_PREFIX\ninfo: ${info}\nheaders: $headers" }
val messageType = headers.get(MESSAGE_TYPE_HEADER)
when (messageType) {
MessageType.FIREBASE.name -> {
val firebaseMessageDto = objectMapper.readValue(info, FirebaseMessageDto::class.java)
FirebaseCloudMessageService.sendMessageTo(firebaseMessageDto.fcmToken, firebaseMessageDto.title, firebaseMessageDto.body)
FirebaseCloudMessageService.sendMessageTo(
firebaseMessageDto.fcmToken,
firebaseMessageDto.title,
firebaseMessageDto.body
)
}

else ->
throw InternalServerException(ErrorCode.INTERNAL_SERVER_EXCEPTION, "${LOG_PREFIX} μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” MessageType(${headers.get(MESSAGE_TYPE_HEADER)} μž…λ‹ˆλ‹€.")
throw InternalServerException(
ErrorCode.INTERNAL_SERVER_EXCEPTION,
"${LOG_PREFIX} μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” MessageType(${headers.get(MESSAGE_TYPE_HEADER)} μž…λ‹ˆλ‹€."
)
}
} catch (exception : Exception) {
} catch (exception: Exception) {
throw Exception(exception.message, exception)
}
}
Expand Down

0 comments on commit e96cb14

Please sign in to comment.