Skip to content

Commit

Permalink
[Feat/#124] kotlin-logger 적용 (#197)
Browse files Browse the repository at this point in the history
* feat: kotlin-logging dependency 추가

* refactor: kotlin logger 디펜던시 상위 위치로 이동

* refactor: kotlin logger 일괄 적용

* chore: booting banner 추가
  • Loading branch information
hun-ca authored Jul 14, 2024
1 parent 6973595 commit 3b21a53
Show file tree
Hide file tree
Showing 13 changed files with 60 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package com.few.api.client.subscription
import com.few.api.client.config.properties.DiscordBodyProperty
import com.few.api.client.config.properties.Embed
import com.few.api.client.subscription.dto.WorkbookSubscriptionArgs
import org.apache.juli.logging.LogFactory
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpEntity
import org.springframework.http.HttpMethod
Expand All @@ -15,7 +15,7 @@ class SubscriptionClient(
private val restTemplate: RestTemplate,
@Value("\${webhook.discord}") private val discordWebhook: String,
) {
private val log = LogFactory.getLog(SubscriptionClient::class.java)
private val log = KotlinLogging.logger {}

fun announceWorkbookSubscription(args: WorkbookSubscriptionArgs) {
args.let {
Expand Down Expand Up @@ -43,7 +43,7 @@ class SubscriptionClient(
HttpEntity(body),
String::class.java
).let { res ->
log.info("Discord webhook response: ${res.statusCode}")
log.info { "Discord webhook response: ${res.statusCode}" }
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions api/src/main/kotlin/com/few/api/config/ApiThreadPoolConfig.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.few.api.config

import com.few.api.config.properties.ThreadPoolProperties
import org.apache.juli.logging.LogFactory
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
Expand All @@ -10,7 +10,7 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
@Configuration
class ApiThreadPoolConfig {

private val log = LogFactory.getLog(ApiThreadPoolConfig::class.java)
private val log = KotlinLogging.logger {}

companion object {
const val DISCORD_HOOK_EVENT_POOL = "discord-task-"
Expand All @@ -32,7 +32,7 @@ class ApiThreadPoolConfig {
setAwaitTerminationSeconds(properties.getAwaitTerminationSeconds())
setThreadNamePrefix("discordHookThreadPool-")
setRejectedExecutionHandler { r, _ ->
log.warn("Discord Hook Event Task Rejected: $r")
log.warn { "Discord Hook Event Task Rejected: $r" }
}
initialize()
}
Expand Down
7 changes: 3 additions & 4 deletions api/src/main/kotlin/com/few/api/web/filter/MDCFilter.kt
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
package com.few.api.web.filter

import com.fasterxml.jackson.databind.ObjectMapper
import io.github.oshai.kotlinlogging.KotlinLogging
import jakarta.servlet.Filter
import jakarta.servlet.FilterChain
import jakarta.servlet.ServletRequest
import jakarta.servlet.ServletResponse
import jakarta.servlet.http.HttpServletRequest
import org.apache.commons.lang3.RandomStringUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import org.springframework.http.HttpHeaders
import org.springframework.stereotype.Component

@Component
class MDCFilter(private val mapper: ObjectMapper) : Filter {
private val log: Logger = LoggerFactory.getLogger(MDCFilter::class.java)
private val log = KotlinLogging.logger {}

override fun doFilter(
request: ServletRequest?,
Expand All @@ -38,7 +37,7 @@ class MDCFilter(private val mapper: ObjectMapper) : Filter {
val requestEndTime = System.currentTimeMillis()
val elapsedTime = requestEndTime - requestStartTime
MDC.put("ElapsedTime", elapsedTime.toString() + "ms")
log.info("{}", mapper.writeValueAsString(MDC.getCopyOfContextMap()))
log.info { mapper.writeValueAsString(MDC.getCopyOfContextMap()) }
MDC.clear()
}
}
4 changes: 2 additions & 2 deletions api/src/main/kotlin/com/few/api/web/handler/LoggingHandler.kt
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package com.few.api.web.handler

import io.github.oshai.kotlinlogging.KotlinLogging
import jakarta.servlet.http.HttpServletRequest
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component

/** 로깅을 담당하는 핸들러 */
@Component
class LoggingHandler {
private val log = LoggerFactory.getLogger(LoggingHandler::class.java)
private val log = KotlinLogging.logger {}

fun writeLog(ex: Exception, request: HttpServletRequest) {
try {
Expand Down
8 changes: 8 additions & 0 deletions api/src/main/resources/banner.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
${AnsiColor.BLUE}
_____________ __
/ ____/ ____/ | / /
/ /_ / __/ | | /| / /
/ __/ / /___ | |/ |/ /
/_/ /_____/ |__/|__/
${application.title} ${application.version}
${AnsiColor.BRIGHT_GREEN}Spring Boot ${AnsiColor.RED}${spring-boot.formatted-version}
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package com.few.api.web.controller

import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.context.ApplicationContextInitializer
import org.springframework.context.ConfigurableApplicationContext
import org.testcontainers.containers.DockerComposeContainer
import java.io.File

class ControllerTestContainerInitializer : ApplicationContextInitializer<ConfigurableApplicationContext> {
private val log: org.slf4j.Logger =
org.slf4j.LoggerFactory.getLogger(ControllerTestContainerInitializer::class.java)
private val log = KotlinLogging.logger {}

companion object {
private const val MYSQL = "mysql"
Expand All @@ -19,10 +19,10 @@ class ControllerTestContainerInitializer : ApplicationContextInitializer<Configu
}

override fun initialize(applicationContext: ConfigurableApplicationContext) {
log.debug("===== set up test containers =====")
log.debug { "===== set up test containers =====" }

dockerCompose.start()

log.debug("===== success set up test containers =====")
log.debug { "===== success set up test containers =====" }
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
package com.few.batch.log

import io.github.oshai.kotlinlogging.KotlinLogging
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.util.*

@Aspect
@Component
class BatchServiceLogAspect {
private val log = LoggerFactory.getLogger(BatchServiceLogAspect::class.java)
private val log = KotlinLogging.logger {}

@Pointcut(value = "execution(* com.few.batch.service..*.execute(..))")
fun batchServiceDao() {}
Expand All @@ -26,11 +26,11 @@ class BatchServiceLogAspect {
val serviceName = splitByDot[splitByDot.size - 1]
val args = joinPoint.args

log.trace("{} execute with {}", serviceName, args)
log.trace { "$serviceName} execute with $args" }
val startTime = System.currentTimeMillis()
val proceed = joinPoint.proceed()
val elapsedTime = System.currentTimeMillis() - startTime
log.debug("{} finished in {}ms", serviceName, elapsedTime)
log.debug { "$serviceName finished in ${elapsedTime}ms" }

return proceed
}
Expand Down
3 changes: 3 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ subprojects {

/** swagger */
swaggerUI("org.webjars:swagger-ui:${DependencyVersion.SWAGGER_UI}")

/** Kotlin Logger **/
implementation("io.github.oshai:kotlin-logging-jvm:${DependencyVersion.KOTLIN_LOGGING}")
}

/** copy data migration */
Expand Down
3 changes: 3 additions & 0 deletions buildSrc/src/main/kotlin/DependencyVersion.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,7 @@ object DependencyVersion {

/** commonmark */
const val COMMONMARK = "0.22.0"

/** Logger **/
const val KOTLIN_LOGGING = "7.0.0"
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ import com.few.storage.document.client.dto.DocumentGetPreSignedObjectUrlArgs
import com.few.storage.document.client.dto.DocumentPutObjectArgs
import com.few.storage.document.client.dto.DocumentWriteResponse
import com.few.storage.document.client.dto.toS3Args
import com.few.storage.image.client.dto.toS3Args
import org.slf4j.LoggerFactory
import io.github.oshai.kotlinlogging.KotlinLogging

class S3DocumentStoreClient(
private val s3client: AmazonS3Client,
private val region: String,
) : DocumentStoreClient {

private val log = LoggerFactory.getLogger(S3DocumentStoreClient::class.java)
private val log = KotlinLogging.logger {}

override fun getPreSignedObjectUrl(args: DocumentGetPreSignedObjectUrlArgs): String? {
args.toS3Args()
Expand All @@ -24,9 +23,9 @@ class S3DocumentStoreClient(
return url.toString()
}
} catch (e: Exception) {
log.debug("Failed to get presigned url for object: ${args.imagePath}")
log.warn(e.message)
log.warn(e.stackTraceToString())
log.debug { "Failed to get presigned url for object: ${args.imagePath}" }
log.warn { e.message }
log.warn { e.stackTraceToString() }
return null
}
}
Expand All @@ -46,9 +45,9 @@ class S3DocumentStoreClient(
)
}
} catch (e: Exception) {
log.debug("Failed to put object: ${args.imagePath}")
log.warn(e.message)
log.warn(e.stackTraceToString())
log.debug { "Failed to put object: ${args.imagePath}" }
log.warn { e.message }
log.warn { e.stackTraceToString() }
return null
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import com.amazonaws.services.s3.AmazonS3Client
import com.few.storage.config.ClientConfig
import com.few.storage.document.client.DocumentStoreClient
import com.few.storage.document.client.S3DocumentStoreClient
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.ApplicationListener
import org.springframework.context.annotation.Bean
Expand All @@ -19,7 +18,7 @@ class S3DocumentStoreConfig(
@Value("\${document.store.bucket-name}") val bucket: String,
@Value("\${storage.region}") val region: String,
) : ApplicationListener<ContextRefreshedEvent> {
var log: Logger = LoggerFactory.getLogger(S3DocumentStoreConfig::class.java)
private val log = KotlinLogging.logger {}

private var client: AmazonS3Client? = null

Expand All @@ -28,9 +27,9 @@ class S3DocumentStoreConfig(
client.listBuckets().let { buckets ->
if (buckets.none { it.name == bucket }) {
client.createBucket(bucket)
log.info("Create bucket $bucket")
log.info { "Create bucket $bucket" }
}
log.info("Bucket $bucket already exists")
log.info { "Bucket $bucket already exists" }
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ package com.few.storage.image.client

import com.amazonaws.services.s3.AmazonS3Client
import com.few.storage.image.client.dto.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import io.github.oshai.kotlinlogging.KotlinLogging

class S3ImageStoreClient(
private val s3client: AmazonS3Client,
private val region: String,
) : ImageStoreClient {

val log: Logger = LoggerFactory.getLogger(S3ImageStoreClient::class.java)
private val log = KotlinLogging.logger {}

override fun getPreSignedObjectUrl(args: ImageGetPreSignedObjectUrlArgs): String? {
args.toS3Args()
Expand All @@ -21,9 +20,9 @@ class S3ImageStoreClient(
return url.toString()
}
} catch (e: Exception) {
log.debug("Failed to get presigned url for object: ${args.imagePath}")
log.warn(e.message)
log.warn(e.stackTraceToString())
log.debug { "Failed to get presigned url for object: ${args.imagePath}" }
log.warn { e.message }
log.warn { e.stackTraceToString() }
return null
}
}
Expand All @@ -36,9 +35,9 @@ class S3ImageStoreClient(
s3client.deleteObject(s3)
return true
} catch (e: Exception) {
log.debug("Failed to remove object: ${args.imagePath}")
log.warn(e.message)
log.warn(e.stackTraceToString())
log.debug { "Failed to remove object: ${args.imagePath}" }
log.warn { e.message }
log.warn { e.stackTraceToString() }
return false
}
}
Expand All @@ -58,9 +57,9 @@ class S3ImageStoreClient(
)
}
} catch (e: Exception) {
log.debug("Failed to put object: ${args.imagePath}")
log.warn(e.message)
log.warn(e.stackTraceToString())
log.debug { "Failed to put object: ${args.imagePath}" }
log.warn { e.message }
log.warn { e.stackTraceToString() }
return null
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ package com.few.storage.image.config
import com.amazonaws.services.s3.AmazonS3Client
import com.few.storage.image.client.ImageStoreClient
import com.few.storage.image.client.S3ImageStoreClient
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.ApplicationListener
import org.springframework.context.annotation.Bean
Expand All @@ -17,7 +16,7 @@ class S3ImageStoreConfig(
@Value("\${storage.region}") val region: String,
) : ApplicationListener<ContextRefreshedEvent> {

var log: Logger = LoggerFactory.getLogger(S3ImageStoreConfig::class.java)
private val log = KotlinLogging.logger {}

private var client: AmazonS3Client? = null

Expand All @@ -26,9 +25,9 @@ class S3ImageStoreConfig(
client.listBuckets().let { buckets ->
if (buckets.none { it.name == bucket }) {
client.createBucket(bucket)
log.info("Create bucket $bucket")
log.info { "Create bucket $bucket" }
}
log.info("Bucket $bucket already exists")
log.info { "Bucket $bucket already exists" }
}
}
}
Expand Down

0 comments on commit 3b21a53

Please sign in to comment.