improve logging

This commit is contained in:
Denis Savosin
2024-10-07 16:32:44 +07:00
parent 02c419f745
commit 377e20b871
7 changed files with 61 additions and 0 deletions

View File

@@ -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)

View 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)