mirror of
https://github.com/Dannecron/spring-boot-demo.git
synced 2025-12-26 08:42:33 +03:00
improve logging
This commit is contained in:
@@ -5,6 +5,8 @@ import com.example.demo.providers.ProductRepository
|
||||
import com.example.demo.services.database.exceptions.AlreadyDeletedException
|
||||
import com.example.demo.services.database.product.exceptions.ProductNotFoundException
|
||||
import com.example.demo.services.kafka.Producer
|
||||
import com.example.demo.utils.LoggerDelegate
|
||||
import net.logstash.logback.marker.Markers
|
||||
import org.springframework.data.domain.Page
|
||||
import org.springframework.data.domain.Pageable
|
||||
import java.time.OffsetDateTime
|
||||
@@ -15,7 +17,15 @@ class ProductServiceImpl(
|
||||
private val productRepository: ProductRepository,
|
||||
private val producer: Producer,
|
||||
): ProductService {
|
||||
private val logger by LoggerDelegate()
|
||||
|
||||
override fun findByGuid(guid: UUID): Product? = productRepository.findByGuid(guid)
|
||||
.also {
|
||||
logger.debug(
|
||||
Markers.appendEntries(mapOf("guid" to guid, "idResult" to it?.id)),
|
||||
"find product by guid",
|
||||
)
|
||||
}
|
||||
|
||||
override fun findAll(pageable: Pageable): Page<Product> = productRepository.findAll(pageable)
|
||||
|
||||
|
||||
24
src/main/kotlin/com/example/demo/utils/Logger.kt
Normal file
24
src/main/kotlin/com/example/demo/utils/Logger.kt
Normal file
@@ -0,0 +1,24 @@
|
||||
package com.example.demo.utils
|
||||
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import kotlin.properties.ReadOnlyProperty
|
||||
import kotlin.reflect.KProperty
|
||||
import kotlin.reflect.full.companionObject
|
||||
|
||||
/**
|
||||
* usage: `private val logger by LoggerDelegate()`
|
||||
*/
|
||||
class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> {
|
||||
override fun getValue(thisRef: R, property: KProperty<*>)
|
||||
= getLogger(getClassForLogging(thisRef.javaClass))
|
||||
|
||||
private fun <T : Any> getClassForLogging(javaClass: Class<T>): Class<*> {
|
||||
return javaClass.enclosingClass?.takeIf {
|
||||
it.kotlin.companionObject?.java == javaClass
|
||||
} ?: javaClass
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fun getLogger(forClass: Class<*>): Logger = LoggerFactory.getLogger(forClass)
|
||||
Reference in New Issue
Block a user