Skip to content

Commit

Permalink
fix logging
Browse files Browse the repository at this point in the history
  • Loading branch information
mobiletoly committed Jun 16, 2020
1 parent f1036c9 commit 97715ec
Show file tree
Hide file tree
Showing 16 changed files with 89 additions and 110 deletions.
5 changes: 2 additions & 3 deletions application/adapters/src/main/kotlin/adapters/AppBootstrap.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import adapters.primary.web.util.respondRestException
import adapters.primary.web.util.throwRestException
import adapters.primary.web.util.toRestErrorResponse
import adapters.util.setProjectDefaults
import com.github.michaelbull.logging.InlineLogger
import io.ktor.application.Application
import io.ktor.application.ApplicationCall
import io.ktor.application.call
Expand All @@ -25,18 +26,16 @@ import io.ktor.request.header
import io.ktor.request.uri
import io.ktor.response.header
import io.ktor.response.respond
import mu.KotlinLogging
import org.jetbrains.exposed.exceptions.ExposedSQLException
import org.koin.ktor.ext.inject
import ports.output.errors.DomainException
import shared.util.e
import java.util.UUID

private val logger = KotlinLogging.logger { }

class AppBootstrap(
application: Application
) {
private val logger = InlineLogger()

init {
val databaseErrorInspector by application.inject<DatabaseErrorInspector>()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package adapters.persistence.addressbook

import adapters.persistence.util.postgresql.pgInsertOrUpdate
import ports.input.RequiresTransactionContext
import shared.util.d
import mu.KotlinLogging
import com.github.michaelbull.logging.InlineLogger
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll

private val logger = KotlinLogging.logger { }
import ports.input.RequiresTransactionContext
import shared.util.d

class AddressBookItemRepository {

private val logger = InlineLogger()

@RequiresTransactionContext
fun getByIdOrNull(id: Long): AddressBookItemSqlEntity? {
return AddressBookItemSqlEntities
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package adapters.persistence.addressbook

import mu.KotlinLogging
import com.github.michaelbull.logging.InlineLogger
import ports.input.RequiresTransactionContext
import ports.models.AddressBookEntry
import ports.output.addressbook.AddressBookEntryNotFoundException
Expand All @@ -9,8 +9,6 @@ import ports.output.addressbook.LoadAddressBookEntryPort
import ports.output.addressbook.SaveAddressBookEntryPort
import shared.util.d

private val logger = KotlinLogging.logger { }

/**
* Adapter to address book item and postal address repositories.
* It can be accessed from Core module only via ports (e.g. LoadAddressBookItemPort to query data).
Expand All @@ -22,6 +20,8 @@ internal class AddressBookPersistenceAdapter(
SaveAddressBookEntryPort,
DeleteAddressBookEntryPort {

private val logger = InlineLogger()

@RequiresTransactionContext
override fun loadAddressBookEntry(id: Long): AddressBookEntry {
val addressBookItemSqlEntity = addressBookItemRepository.getByIdOrNull(id = id)
Expand Down Expand Up @@ -53,7 +53,9 @@ internal class AddressBookPersistenceAdapter(

@RequiresTransactionContext
override fun addAddressBookEntry(addressBookEntry: AddressBookEntry): AddressBookEntry {
logger.d("addAddressBookEntry") { "Add AddressBookEntry: $addressBookEntry" }
logger.d("addAddressBookEntry") {
"Add AddressBookEntry: $addressBookEntry"
}
require(addressBookEntry.id == null) { "addressBookItem.id must be null" }
return upsertAddressBookEntry(addressBookEntry = addressBookEntry, postalAddressId = null)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
package adapters.persistence.addressbook

import adapters.persistence.util.postgresql.pgInsertOrUpdate
import ports.input.RequiresTransactionContext
import shared.util.d
import mu.KotlinLogging
import org.jetbrains.exposed.sql.deleteWhere
import com.github.michaelbull.logging.InlineLogger
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll

private val logger = KotlinLogging.logger { }
import ports.input.RequiresTransactionContext
import shared.util.d

class PostalAddressRepository {

private val logger = InlineLogger()

@RequiresTransactionContext
fun getById(id: Long): PostalAddressSqlEntity {
return PostalAddressSqlEntities
Expand Down Expand Up @@ -51,19 +51,6 @@ class PostalAddressRepository {
}
}

@RequiresTransactionContext
fun getByIds(ids: Collection<Long>): Map<Long, PostalAddressSqlEntity> {
return PostalAddressSqlEntities
.select {
PostalAddressSqlEntities.id inList ids
}
.map {
val postalAddress = PostalAddressSqlEntity.fromSqlResultRow(it)
postalAddress.id!! to postalAddress
}
.toMap()
}

@RequiresTransactionContext
fun getAll(): List<PostalAddressSqlEntity> {
return PostalAddressSqlEntities
Expand All @@ -72,27 +59,4 @@ class PostalAddressRepository {
PostalAddressSqlEntity.fromSqlResultRow(it)
}
}

@RequiresTransactionContext
fun deleteById(id: Long): Boolean {
return PostalAddressSqlEntities
.deleteWhere {
PostalAddressSqlEntities.id eq id
} > 0
}

@RequiresTransactionContext
fun deleteByAddressBookItemId(id: Long): Boolean {
return PostalAddressSqlEntities
.deleteWhere {
PostalAddressSqlEntities.addressBookItemId eq id
} > 0
}

@RequiresTransactionContext
fun count(): Long {
return PostalAddressSqlEntities
.selectAll()
.count()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ package adapters.primary.web.util
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.exc.InvalidFormatException
import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException
import com.github.michaelbull.logging.InlineLogger
import io.ktor.application.ApplicationCall
import io.ktor.http.HttpStatusCode
import io.ktor.request.receive
import io.ktor.request.uri
import io.ktor.response.respond
import mu.KotlinLogging
import shared.util.d
import shared.util.w

private val logger = KotlinLogging.logger { }
private val logger = InlineLogger()

internal suspend inline fun <reified T : Any> ApplicationCall.receiveValidated(): T {
return try {
Expand Down Expand Up @@ -48,7 +48,7 @@ private fun raiseInvalidRequestParameterFormatException(name: String, e: Excepti
}

private fun handleReceiveWithValidationException(e: Exception): Nothing {
logger.d("handleReceiveWithValidationException", e) {
logger.w("handleReceiveWithValidationException", e) {
"Exception has been raised while deserializing payload"
}
when (e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package adapters.remoting
import adapters.primary.web.util.RestExternalServiceCallException
import adapters.util.sharedJsonMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.github.michaelbull.logging.InlineLogger
import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.features.ClientRequestException
Expand All @@ -20,13 +21,12 @@ import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.readBytes
import io.ktor.http.ContentType
import io.ktor.http.contentType
import mu.KotlinLogging
import shared.util.e

private val logger = KotlinLogging.logger { }

internal class HttpClientFactoryImpl : HttpClientFactory {

private val logger = InlineLogger()

private val _httpClient by lazy {
HttpClient(OkHttp) {
engine {
Expand Down Expand Up @@ -55,32 +55,32 @@ internal class HttpClientFactoryImpl : HttpClientFactory {
}

override fun httpClient() = _httpClient
}

/**
* Map HTTP response status to RestExternalServiceCallException with response payload (if possible).
*/
private suspend fun HttpResponse.throwException(): Nothing {
val errorMap = try {
// At first we will try to exract response payload and map it to JSON structure of plain text
val body = readBytes()
if (contentType()?.contentType?.contains(ContentType.Application.Json.contentType) == true) {
sharedJsonMapper.readValue<Map<String, Any>>(body)
} else {
mapOf("responseBody" to String(body))
}
} catch (e: Throwable) {
logger.e("HttpResponse.throwException()") { "Failed to map error response" }
// If previous attempt of mapping failed - we fallback to default behavior
when (status.value) {
in 300..399 -> throw RedirectResponseException(this)
in 400..499 -> throw ClientRequestException(this)
in 500..599 -> throw ServerResponseException(this)
/**
* Map HTTP response status to RestExternalServiceCallException with response payload (if possible).
*/
private suspend fun HttpResponse.throwException(): Nothing {
val errorMap = try {
// At first we will try to exract response payload and map it to JSON structure of plain text
val body = readBytes()
if (contentType()?.contentType?.contains(ContentType.Application.Json.contentType) == true) {
sharedJsonMapper.readValue<Map<String, Any>>(body)
} else {
mapOf("responseBody" to String(body))
}
} catch (e: Throwable) {
logger.e("HttpResponse.throwException()") { "Failed to map error response" }
// If previous attempt of mapping failed - we fallback to default behavior
when (status.value) {
in 300..399 -> throw RedirectResponseException(this)
in 400..499 -> throw ClientRequestException(this)
in 500..599 -> throw ServerResponseException(this)
}
throw ResponseException(this)
}
throw ResponseException(this)
throw RestExternalServiceCallException(
status = status,
specifics = errorMap
)
}
throw RestExternalServiceCallException(
status = status,
specifics = errorMap
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@ package adapters.remoting.randomperson
import adapters.config.AppConfig
import adapters.remoting.HttpClientFactory
import adapters.remoting.randomperson.dto.RandomPersonResponseDto
import com.github.michaelbull.logging.InlineLogger
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import mu.KotlinLogging
import shared.util.d

private val logger = KotlinLogging.logger { }

internal class RandomPersonHttpClient(
private val appConfig: AppConfig,
private val httpClientFactory: HttpClientFactory
) {
private val logger = InlineLogger()

suspend fun fetchRandomPerson(): RandomPersonResponseDto {
logger.d("fetchRandomPerson") { "Perform HTTP GET request to URL=${appConfig.randomPerson.fetchUrl}" }
Expand Down
11 changes: 9 additions & 2 deletions application/configuration/src/main/resources/logback.xml
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - request-id=%X{mdc-callid} - %msg%n</pattern>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - request-id=%X{mdc-callid} - %msg%n</pattern>
</encoder>
</appender>

<root level="DEBUG">
<appender-ref ref="STDOUT"/>
</root>

<logger name="io.netty" level="INFO"/>
<logger name="io.netty" level="DEBUG"/>
<logger name="com.zaxxer.hikari" level="INFO"/>
<logger name="org.apache.http" level="INFO"/>
<logger name="com.github.dockerjava" level="WARN"/>
<logger name="org.testcontainers" level="INFO"/>
<logger name="Exposed" level="INFO"/>

<logger name="adapters" level="DEBUG"/>
<logger name="configuration" level="DEBUG"/>
<logger name="core" level="DEBUG"/>
<logger name="ports" level="DEBUG"/>
<logger name="shared" level="DEBUG"/>

</configuration>
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import ports.output.errors.ResourceNotFoundException

object DeleteAddressBookEntryRouteTest : AppRouteSpek({

describe("HTTP DELETE /addressBookItem/:id") {
describe("HTTP DELETE /addressBookEntries/:id") {
context("with record id not in database") {
it("returns HTTP 204 No Content with existing record") {
withApp {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import ports.output.errors.ResourceNotFoundException

object LoadAddressBookEntryRouteTest : AppRouteSpek({

describe("HTTP GET /addressBookItem/:id") {
describe("HTTP GET /addressBookEntries/:id") {
context("with :id matching existing record") {
it("returns HTTP 200 OK with existing record") {
withApp {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import ports.output.errors.ResourceNotFoundException

object SaveAddressBookEntryRouteTest : AppRouteSpek({

describe("HTTP POST /addressBookItem") {
describe("HTTP POST /addressBookEntries") {
context("with unique and valid payload") {
it("adds record and returns HTTP 201 Created with payload") {
withApp {
Expand Down Expand Up @@ -78,7 +78,7 @@ object SaveAddressBookEntryRouteTest : AppRouteSpek({
}
}

describe("HTTP PUT /addressBookItem") {
describe("HTTP PUT /addressBookEntries") {
context("with id of existing record") {
it("update existing record and returns HTTP 200 OK") {
withApp {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - request-id=%X{mdc-callid} - %msg%n</pattern>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - request-id=%X{mdc-callid} - %msg%n</pattern>
</encoder>
</appender>

Expand All @@ -14,5 +14,12 @@
<logger name="org.apache.http" level="INFO"/>
<logger name="com.github.dockerjava" level="WARN"/>
<logger name="org.testcontainers" level="INFO"/>
<logger name="Exposed" level="INFO"/>

<logger name="adapters" level="DEBUG"/>
<logger name="configuration" level="DEBUG"/>
<logger name="core" level="DEBUG"/>
<logger name="ports" level="DEBUG"/>
<logger name="shared" level="DEBUG"/>

</configuration>
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package core.addressbook

import ports.models.AddressBookEntry
import ports.input.RequiresTransactionContext
import ports.input.TransactionService
import ports.input.addressbook.LoadAddressBookEntryByIdUseCase
import ports.input.addressbook.LoadAddressBookEntryByIdUseCase.LoadAddressBookEntryByIdUseCaseCommand
import ports.input.addressbook.LoadAllAddressBookEntriesUseCase
import ports.models.AddressBookEntry
import ports.output.addressbook.LoadAddressBookEntryPort

/**
Expand Down
Loading

0 comments on commit 97715ec

Please sign in to comment.