Skip to content

Commit e96cb14

Browse files
authored
✨: apply global KLogger #18 (#19)
1 parent 09ed7e6 commit e96cb14

File tree

8 files changed

+63
-46
lines changed

8 files changed

+63
-46
lines changed

β€Žbuild.gradle.kts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,10 @@ subprojects {
4444
compileOnly("org.projectlombok:lombok")
4545
annotationProcessor("org.projectlombok:lombok")
4646

47+
// kotlin
4748
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
4849
implementation("org.jetbrains.kotlin:kotlin-reflect")
50+
implementation("io.github.oshai:kotlin-logging-jvm:5.1.0")
4951

5052
testImplementation("org.springframework.boot:spring-boot-starter-test")
5153
}

β€Žplu-api/src/main/kotlin/com/th/plu/api/service/auth/jwt/JwtHandler.kt

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.th.plu.api.service.auth.jwt
22

33
import com.th.plu.api.service.redis.RedisHandler
4+
import com.th.plu.common.Slf4JKotlinLogging.log
45
import com.th.plu.common.constant.JwtKey
56
import com.th.plu.common.constant.RedisKey
67
import com.th.plu.common.exception.code.ErrorCode
@@ -10,7 +11,6 @@ import io.jsonwebtoken.io.Decoders
1011
import io.jsonwebtoken.io.DecodingException
1112
import io.jsonwebtoken.security.Keys
1213
import jakarta.annotation.PostConstruct
13-
import org.slf4j.LoggerFactory
1414
import org.springframework.beans.factory.annotation.Value
1515
import org.springframework.stereotype.Component
1616
import java.security.Key
@@ -23,7 +23,6 @@ class JwtHandler(
2323
@Value("\${jwt.secret}")
2424
private var jwtSecret: String? = null
2525
private var secretKey: Key? = null
26-
private val log = LoggerFactory.getLogger(this.javaClass)
2726

2827
companion object {
2928
// private const val ACCESS_TOKEN_EXPIRE_TIME = 10 * 60 * 1000L // 10λΆ„
@@ -71,19 +70,19 @@ class JwtHandler(
7170
Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token)
7271
return true
7372
} catch (e: SecurityException) {
74-
log.warn("Invalid JWT Token", e)
73+
log.warn(e) { "Invalid JWT Token" }
7574
} catch (e: MalformedJwtException) {
76-
log.warn("Invalid JWT Token", e)
75+
log.warn(e) { "Invalid JWT Token" }
7776
} catch (e: DecodingException) {
78-
log.warn("Invalid JWT Token", e)
77+
log.warn(e) { "Invalid JWT Token" }
7978
} catch (e: ExpiredJwtException) {
80-
log.warn("Expired JWT Token", e)
79+
log.warn(e) { "Expired JWT Token" }
8180
} catch (e: UnsupportedJwtException) {
82-
log.warn("Unsupported JWT Token", e)
81+
log.warn(e) { "Unsupported JWT Token" }
8382
} catch (e: IllegalArgumentException) {
84-
log.warn("JWT claims string is empty.", e)
83+
log.warn(e) { "JWT claims string is empty." }
8584
} catch (e: Exception) {
86-
log.error("Unhandled JWT exception", e)
85+
log.error(e) { "Unhandled JWT exception" }
8786
}
8887
return false
8988
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.th.plu.common
2+
3+
import io.github.oshai.kotlinlogging.KLogger
4+
import io.github.oshai.kotlinlogging.KotlinLogging
5+
6+
object Slf4JKotlinLogging {
7+
val <reified T> T.log: KLogger
8+
inline get() = KotlinLogging.logger {}
9+
}

β€Žplu-common/src/main/kotlin/com/th/plu/common/aop/advice/ExceptionControllerAdvice.kt

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
package com.th.plu.common.aop.advice
22

33
import com.fasterxml.jackson.databind.exc.InvalidFormatException
4+
import com.th.plu.common.Slf4JKotlinLogging.log
45
import com.th.plu.common.dto.response.ApiResponse
56
import com.th.plu.common.exception.code.ErrorCode
67
import com.th.plu.common.exception.model.*
7-
import org.slf4j.LoggerFactory
88
import org.springframework.http.HttpStatus
99
import org.springframework.http.converter.HttpMessageNotReadableException
1010
import org.springframework.validation.BindException
@@ -20,22 +20,20 @@ import org.springframework.web.servlet.resource.NoResourceFoundException
2020

2121
@RestControllerAdvice
2222
class ExceptionControllerAdvice {
23-
private val log = LoggerFactory.getLogger(this.javaClass)
24-
2523
/**
2624
* 400 Bad Request
2725
*/
2826
@ResponseStatus(HttpStatus.BAD_REQUEST)
2927
@ExceptionHandler(ValidationException::class)
3028
fun handleValidationException(exception: ValidationException): ApiResponse<Any> {
31-
log.error(exception.message)
29+
log.error(exception) { exception.message }
3230
return ApiResponse.error(exception.errorCode)
3331
}
3432

3533
@ResponseStatus(HttpStatus.BAD_REQUEST)
3634
@ExceptionHandler(MethodArgumentNotValidException::class)
3735
fun handleMethodArgumentNotValidException(exception: MethodArgumentNotValidException): ApiResponse<Any> {
38-
log.error(exception.message, exception);
36+
log.error(exception) { exception.message }
3937
return ApiResponse.error(
4038
ErrorCode.METHOD_ARGUMENT_NOT_VALID_EXCEPTION,
4139
exception.bindingResult.fieldError?.defaultMessage.toString()
@@ -45,7 +43,7 @@ class ExceptionControllerAdvice {
4543
@ResponseStatus(HttpStatus.BAD_REQUEST)
4644
@ExceptionHandler(BindException::class)
4745
fun handleBindException(exception: BindException): ApiResponse<Any> {
48-
log.error(exception.message, exception);
46+
log.error(exception) { exception.message }
4947
return ApiResponse.error(
5048
ErrorCode.BIND_EXCEPTION,
5149
exception.bindingResult.fieldError?.defaultMessage.toString()
@@ -61,7 +59,7 @@ class ExceptionControllerAdvice {
6159
]
6260
)
6361
fun handleInvalidFormatException(exception: Exception): ApiResponse<Any> {
64-
log.error(exception.message, exception);
62+
log.error(exception) { exception.message }
6563
return ApiResponse.error(ErrorCode.INVALID_FORMAT_EXCEPTION);
6664
}
6765

@@ -71,7 +69,7 @@ class ExceptionControllerAdvice {
7169
@ResponseStatus(HttpStatus.UNAUTHORIZED)
7270
@ExceptionHandler(UnauthorizedException::class)
7371
fun handleUnauthorizedException(exception: UnauthorizedException): ApiResponse<Any> {
74-
log.error(exception.message, exception)
72+
log.error(exception) { exception.message }
7573
return ApiResponse.error(exception.errorCode)
7674
}
7775

@@ -81,7 +79,7 @@ class ExceptionControllerAdvice {
8179
@ResponseStatus(HttpStatus.FORBIDDEN)
8280
@ExceptionHandler(ForbiddenException::class)
8381
fun handleForbiddenException(exception: ForbiddenException): ApiResponse<Any> {
84-
log.error(exception.message, exception)
82+
log.error(exception) { exception.message }
8583
return ApiResponse.error(exception.errorCode)
8684
}
8785

@@ -91,7 +89,7 @@ class ExceptionControllerAdvice {
9189
@ResponseStatus(HttpStatus.NOT_FOUND)
9290
@ExceptionHandler(NotFoundException::class)
9391
fun handleNotFoundException(exception: NotFoundException): ApiResponse<Any> {
94-
log.error(exception.message, exception)
92+
log.error(exception) { exception.message }
9593
return ApiResponse.error(exception.errorCode)
9694
}
9795

@@ -102,7 +100,7 @@ class ExceptionControllerAdvice {
102100
NoResourceFoundException::class]
103101
)
104102
fun handleNotFoundEndpointException(exception: Exception): ApiResponse<Any> {
105-
log.error(exception.message, exception)
103+
log.error(exception) { exception.message }
106104
return ApiResponse.error(ErrorCode.NOT_FOUND_ENDPOINT_EXCEPTION)
107105
}
108106

@@ -121,7 +119,7 @@ class ExceptionControllerAdvice {
121119
@ResponseStatus(HttpStatus.CONFLICT)
122120
@ExceptionHandler(ConflictException::class)
123121
fun handleConflictException(exception: ConflictException): ApiResponse<Any> {
124-
log.error(exception.message, exception)
122+
log.error(exception) { exception.message }
125123
return ApiResponse.error(exception.errorCode)
126124
}
127125

@@ -140,7 +138,7 @@ class ExceptionControllerAdvice {
140138
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
141139
@ExceptionHandler(Exception::class)
142140
fun handleInternalServerException(exception: Exception): ApiResponse<Any> {
143-
log.error(exception.message, exception)
141+
log.error(exception) { exception.message }
144142
return ApiResponse.error(ErrorCode.INTERNAL_SERVER_EXCEPTION)
145143
}
146144

@@ -150,7 +148,7 @@ class ExceptionControllerAdvice {
150148
@ResponseStatus(HttpStatus.BAD_GATEWAY)
151149
@ExceptionHandler(BadGatewayException::class)
152150
fun handleBadGatewayException(exception: BadGatewayException): ApiResponse<Any> {
153-
log.error(exception.message, exception)
151+
log.error(exception) { exception.message }
154152
return ApiResponse.error(exception.errorCode)
155153
}
156154
}

β€Žplu-external/src/main/kotlin/com/th/plu/external/client/firebase/WebClientFirebaseApiCaller.kt

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
package com.th.plu.external.client.firebase
22

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

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

2523

@@ -33,19 +31,25 @@ class WebClientFirebaseApiCaller(private val webClient: WebClient) : FirebaseApi
3331
.body(BodyInserters.fromValue<String>(message))
3432
.retrieve()
3533
.onStatus(HttpStatusCode::is4xxClientError) {
36-
Mono.error(BadGatewayException(ErrorCode.BAD_GATEWAY_EXCEPTION,
37-
createFirebaseFailMessage(it, message)
38-
))
34+
Mono.error(
35+
BadGatewayException(
36+
ErrorCode.BAD_GATEWAY_EXCEPTION,
37+
createFirebaseFailMessage(it, message)
38+
)
39+
)
3940
}
4041
.onStatus(HttpStatusCode::is5xxServerError) {
41-
Mono.error(BadGatewayException(ErrorCode.BAD_GATEWAY_EXCEPTION,
42-
createFirebaseFailMessage(it, message)
43-
))
42+
Mono.error(
43+
BadGatewayException(
44+
ErrorCode.BAD_GATEWAY_EXCEPTION,
45+
createFirebaseFailMessage(it, message)
46+
)
47+
)
4448
}
4549
.toBodilessEntity()
4650
.subscribe {
4751
if (it.statusCode.is2xxSuccessful) {
48-
log.info("${LOG_PREFIX}\nStatus: ${it.statusCode}\nMessage: ${message}")
52+
log.info { "${LOG_PREFIX}\nStatus: ${it.statusCode}\nMessage: ${message}" }
4953
} else {
5054
throw BadGatewayException(
5155
ErrorCode.BAD_GATEWAY_EXCEPTION,

β€Žplu-external/src/main/kotlin/com/th/plu/external/sqs/sender/SqsSenderImpl.kt

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
package com.th.plu.external.sqs.sender
22

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

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

2322
override fun sendFirebaseMessage(message: FirebaseMessageDto): SendResult<String> {
24-
log.info("${LOG_PREFIX} send Message(type: ${message.type})")
23+
log.info { "$LOG_PREFIX send Message(type: ${message.type})" }
2524
return sqsTemplate.send {
2625
it.queue(queueName.toString())
2726
it.header(MESSAGE_TYPE_HEADER, message.type.name)

β€Žplu-notification/src/main/kotlin/com/th/plu/notification/firebase/FirebaseCloudMessageService.kt

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ package com.th.plu.notification.firebase
22

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

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

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

4746
return googleCredentials.accessToken.tokenValue
4847
} catch (exception: Exception) {
49-
log.error(exception.message, exception)
48+
log.error(exception) { exception.message }
5049
throw BadGatewayException(
5150
ErrorCode.BAD_GATEWAY_EXCEPTION,
52-
"${LOG_PREFIX} FCM Access Token λ°œκΈ‰ κ³Όμ •μ—μ„œ μ—λŸ¬κ°€ λ°œμƒν•˜μ˜€μŠ΅λ‹ˆλ‹€."
51+
"$LOG_PREFIX FCM Access Token λ°œκΈ‰ κ³Όμ •μ—μ„œ μ—λŸ¬κ°€ λ°œμƒν•˜μ˜€μŠ΅λ‹ˆλ‹€."
5352
)
5453
}
5554
}

β€Žplu-notification/src/main/kotlin/com/th/plu/notification/sqs/SqsConsumer.kt

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
package com.th.plu.notification.sqs
22

33
import com.fasterxml.jackson.databind.ObjectMapper
4+
import com.th.plu.common.Slf4JKotlinLogging.log
45
import com.th.plu.common.exception.code.ErrorCode
56
import com.th.plu.common.exception.model.InternalServerException
67
import com.th.plu.external.sqs.dto.FirebaseMessageDto
78
import com.th.plu.external.sqs.dto.MessageType
89
import com.th.plu.notification.firebase.FirebaseCloudMessageService
910
import io.awspring.cloud.sqs.annotation.SqsListener
10-
import org.slf4j.LoggerFactory
1111
import org.springframework.messaging.handler.annotation.Headers
1212
import org.springframework.messaging.handler.annotation.Payload
1313
import org.springframework.stereotype.Service
@@ -17,25 +17,32 @@ class SqsConsumer(
1717
private val objectMapper: ObjectMapper,
1818
private val FirebaseCloudMessageService: FirebaseCloudMessageService
1919
) {
20-
private val log = LoggerFactory.getLogger(this.javaClass)
2120
private val LOG_PREFIX = "====> [SQS Queue Request]";
2221

2322
private val MESSAGE_TYPE_HEADER = "type"
2423

2524
@SqsListener("pluNotification.fifo")
2625
fun consume(@Payload info: String, @Headers headers: Map<String, String>) {
2726
try {
28-
log.info("${LOG_PREFIX}\ninfo: ${info}\nheaders: ${headers}")
27+
log.info { "$LOG_PREFIX\ninfo: ${info}\nheaders: $headers" }
2928
val messageType = headers.get(MESSAGE_TYPE_HEADER)
3029
when (messageType) {
3130
MessageType.FIREBASE.name -> {
3231
val firebaseMessageDto = objectMapper.readValue(info, FirebaseMessageDto::class.java)
33-
FirebaseCloudMessageService.sendMessageTo(firebaseMessageDto.fcmToken, firebaseMessageDto.title, firebaseMessageDto.body)
32+
FirebaseCloudMessageService.sendMessageTo(
33+
firebaseMessageDto.fcmToken,
34+
firebaseMessageDto.title,
35+
firebaseMessageDto.body
36+
)
3437
}
38+
3539
else ->
36-
throw InternalServerException(ErrorCode.INTERNAL_SERVER_EXCEPTION, "${LOG_PREFIX} μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” MessageType(${headers.get(MESSAGE_TYPE_HEADER)} μž…λ‹ˆλ‹€.")
40+
throw InternalServerException(
41+
ErrorCode.INTERNAL_SERVER_EXCEPTION,
42+
"${LOG_PREFIX} μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” MessageType(${headers.get(MESSAGE_TYPE_HEADER)} μž…λ‹ˆλ‹€."
43+
)
3744
}
38-
} catch (exception : Exception) {
45+
} catch (exception: Exception) {
3946
throw Exception(exception.message, exception)
4047
}
4148
}

0 commit comments

Comments
Β (0)