|
| 1 | +package software.bevel.code_to_knowledge_graph.vscode |
| 2 | + |
| 3 | +import ch.qos.logback.classic.Level |
| 4 | +import ch.qos.logback.classic.Logger |
| 5 | +import ch.qos.logback.classic.turbo.TurboFilter |
| 6 | +import ch.qos.logback.core.spi.FilterReply |
| 7 | +import org.slf4j.Marker |
| 8 | + |
| 9 | +/** |
| 10 | + * A custom Logback TurboFilter that throws exceptions when ERROR level logs are encountered during tests. |
| 11 | + * This helps ensure that error logging paths can be properly tested by causing test failures |
| 12 | + * when log.error() is called. |
| 13 | + */ |
| 14 | +class ErrorToExceptionTurboFilter : TurboFilter() { |
| 15 | + |
| 16 | + override fun decide( |
| 17 | + marker: Marker?, |
| 18 | + logger: Logger?, |
| 19 | + level: Level?, |
| 20 | + format: String?, |
| 21 | + params: Array<out Any>?, |
| 22 | + t: Throwable? |
| 23 | + ): FilterReply { |
| 24 | + // Only throw exceptions for ERROR level logs |
| 25 | + if (level == Level.ERROR) { |
| 26 | + val errorMessage = if (format != null && params != null) { |
| 27 | + formatMessage(format, params) |
| 28 | + } else { |
| 29 | + format ?: "Unknown error" |
| 30 | + } |
| 31 | + |
| 32 | + val exception = t ?: RuntimeException("Error logged: $errorMessage") |
| 33 | + |
| 34 | + // Throw a runtime exception with the log message and original cause |
| 35 | + throw RuntimeException("Error logged via SLF4J: $errorMessage", exception) |
| 36 | + } |
| 37 | + |
| 38 | + // For all other log levels, continue normal processing |
| 39 | + return FilterReply.NEUTRAL |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Simple formatter for log messages that contain parameters |
| 44 | + */ |
| 45 | + private fun formatMessage(format: String, params: Array<out Any>): String { |
| 46 | + var result = format |
| 47 | + params.forEach { param -> |
| 48 | + result = result.replaceFirst("{}", param.toString()) |
| 49 | + } |
| 50 | + return result |
| 51 | + } |
| 52 | +} |
0 commit comments