Skip to content

Commit

Permalink
fix(logging): make table and constraint checks more consistent
Browse files Browse the repository at this point in the history
  • Loading branch information
saku-koodari committed Jan 8, 2025
1 parent 67bbb19 commit df68267
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 17 deletions.
3 changes: 2 additions & 1 deletion server/src/main/kotlin/fi/oph/kitu/logging/EventLogger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ class EventLogger<T>(
val duplicateKeyException = (if (ex is DuplicateKeyException) ex else ex.cause) as DuplicateKeyException

val table =
duplicateKeyException.message
duplicateKeyException.cause
?.message
?.substringAfter("INSERT INTO \"")
?.substringBefore("\"")

Expand Down
29 changes: 13 additions & 16 deletions server/src/test/kotlin/fi/oph/kitu/logging/EventLoggerTests.kt
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ class EventLoggerTests {
fun `addDatabaseLogs do database logging when it throws DuplicateKeyException`() {
val event = MockEvent()
val actionToRun = {
val cause = DuplicateKeyException("unique constraint \"my_constraint \"")

throw DuplicateKeyException("INSERT INTO \"my_table\"", cause)
throw DuplicateKeyException("INSERT INTO \"my_table\" unique constraint \"my_constraint\"")
}

// runCatching is eager so it runs the action.
Expand All @@ -92,23 +90,19 @@ class EventLoggerTests {
assertThrows<DuplicateKeyException> {
logger.getOrThrow()
}

val table = event.getValueOrNullByKey<String>("table")
assertEquals("my_table", table)

val constraint = event.getValueOrNullByKey<String>("constraint")
assertEquals("my_constraint", constraint)
}

@Test
fun `withEventAndPerformanceCheck does performance logging when running an action`() {
val event = MockEvent()
val logger = MockLogger(event)

logger.atInfo().withEventAndPerformanceCheck {
// Action runs succesfully
Thread.sleep(1)
}
logger
.atInfo()
.withEventAndPerformanceCheck {
// Action runs succesfully
Thread.sleep(1)
}.getOrThrow()

val durationMs = event.getValueOrNullByKey<Long>("duration_ms")
assertNotNull(durationMs, "duration_ms should not be null")
Expand All @@ -126,9 +120,12 @@ class EventLoggerTests {
val logger = MockLogger(event)

assertThrows<ExceptionThatThrows> {
logger.atInfo().withEvent("unit-test") {
throw ExceptionThatThrows("Expected error")
}
logger
.atInfo()
.withEventAndPerformanceCheck {
Thread.sleep(1)
throw ExceptionThatThrows("Expected error")
}.getOrThrow()
}

val durationMs = event.getValueOrNullByKey<Long>("duration_ms")
Expand Down

0 comments on commit df68267

Please sign in to comment.