Repository navigation
Avoid SLF4J 2-only Logger API in logging helpers - #3432
Conversation
ExceptionUtil, ForeignFunctions#logThrowable, and PerfDataUtil#handleError used Logger#atLevel/setCause and Logger#isEnabledForLevel, which only exist in slf4j-api 2.x. Replace them with a per-file level-switch that dispatches to the classic error/warn/info/debug/trace methods, relying on SLF4J's implicit-cause handling (a trailing Throwable argument is attached as the log event's cause rather than substituted into the format string) to keep identical log output. This removes the last compile-time dependency on the 2.x API surface without changing the slf4j.version dependency itself.
The pre-refactor code guarded each log call with an isXEnabled() check before formatting the PDH error code, to avoid that formatting cost when the target level is disabled. That guard was dropped when isEnabledForLevel (slf4j 2.x-only) was swapped for the level-switch. Add an isEnabled(Level) helper using the same switch-on-level pattern to restore the guard with 1.x-compatible API.
Merge the two level-switches into one, and extract the PDH error message formatting into its own method so it's only built inside the enabled branches rather than passed in as pre-formatted varargs.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (6)
📜 Recent review details⏰ Context from checks skipped due to timeout. (15)
🧰 Additional context used🧠 Learnings (3)📚 Learning: 2026-05-31T05:53:04.246ZApplied to files:
📚 Learning: 2026-07-06T19:25:59.225ZApplied to files:
📚 Learning: 2026-04-12T19:22:09.716ZApplied to files:
🔇 Additional comments (8)
📝 WalkthroughWalkthroughThis PR replaces fluent SLF4J ChangesLevel-based logging compatibility
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #3432 +/- ##
============================================
- Coverage 75.22% 75.12% -0.11%
Complexity 76 76
============================================
Files 580 580
Lines 21589 21609 +20
Branches 3583 3588 +5
============================================
- Hits 16241 16234 -7
- Misses 3326 3341 +15
- Partials 2022 2034 +12
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@oshi-common/src/main/java/oshi/util/ExceptionUtil.java`:
- Around line 26-56: ExceptionUtil.logAtLevel is passing the throwable through a
normal two-argument logger call, so the cause and stack trace are not preserved.
Update logAtLevel in ExceptionUtil to use the SLF4J overloads that accept a
Throwable as the last argument, ensuring t is attached as the log cause for each
Level case while still formatting the message placeholder correctly.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 3ab214c7-a295-4bd7-8745-e4a2a097b441
📒 Files selected for processing (3)
oshi-common/src/main/java/oshi/util/ExceptionUtil.javaoshi-core-ffm/src/main/java/oshi/ffm/ForeignFunctions.javaoshi-core/src/main/java/oshi/util/platform/windows/PerfDataUtil.java
📜 Review details
⏰ Context from checks skipped due to timeout. (3)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
- GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.
Applied to files:
oshi-common/src/main/java/oshi/util/ExceptionUtil.java
🔇 Additional comments (3)
oshi-common/src/main/java/oshi/util/ExceptionUtil.java (1)
190-190: LGTM!Also applies to: 240-240, 290-290, 341-341, 392-392, 425-425, 457-457, 489-489, 530-530
oshi-core-ffm/src/main/java/oshi/ffm/ForeignFunctions.java (1)
484-506: LGTM!oshi-core/src/main/java/oshi/util/platform/windows/PerfDataUtil.java (1)
161-195: LGTM!
|
Thanks @wolfs! I bumped into this in my earlier Sonar cleanup and thought I got all of them but obviously missed a few.
Agreed, OSHI's philosophy has always been to maximize compatibility. A few requests before merge:
<profiles>
<profile>
<id>verify-slf4j-17</id>
<properties>
<slf4j.version>1.7.36</slf4j.version>
</properties>
</profile>
</profiles>CI job (fails the build if anyone reintroduces 2.0-only API): ./mvnw -Pverify-slf4j-17 clean compile
<osgi.slf4j.import.packages>org.slf4j;version="[1.7,3.0)",org.slf4j.event;version="[1.7,3.0)"</osgi.slf4j.import.packages>
|
|
One other request, add a test to validate we cover all the @Test
void testLogsAndReturnsDefaultAtEveryLevel() {
for (Level level : Level.values()) {
String result = ExceptionUtil.getOrDefault(() -> {
throw new IllegalStateException("boom");
}, "no exception", LOG, level, "failed: {}");
assertThat(result, is("no exception"));
}
}Similarly for PerfDataUtil changes. Yes, this is just exercising code to gain coverage as we can't really test the log messages but I think validating all enum values are handled is at least useful. |
Add a Maven profile that overrides slf4j.version to 1.7.36 and a lint-job CI step that compiles under it, so any future use of SLF4J 2.0-only Logger methods (atLevel, isEnabledForLevel, LoggingEventBuilder, etc.) fails the build instead of silently breaking consumers who pin an older slf4j-api on the runtime classpath.
The bnd-generated manifest pinned org.slf4j.event to [2.0,3) even though org.slf4j itself was already widened to [1.7,3.0). Level has existed since slf4j 1.7.15, so it's runtime-safe on 1.7 - only the OSGi import range needed updating to match.
oshi-core-ffm already depends on oshi-common, so its level-switch duplicated ExceptionUtil.logAtLevel. Make that method public and reuse it here instead of maintaining two copies of the same dispatch.
Loop over Level.values() in both handleError/getOrDefault to exercise every switch branch (including the DEBUG/default case), closing the coverage gap left when the fluent atLevel API was replaced with explicit switches.
|
Thanks for the quick response to the review! Great contribution. I really appreciate you (and others in the community) reporting the inevitable bugs from the latest module split and refactoring. Merging. |
|
@dbwiddis Happy to help. Thank you for the quick turnaround! Do you already know when you'll cut a release including these new changes? |
PerfDataUtil.handleError and ExceptionUtil.logAtLevel each carried their own five-way LogLevel switch. Hoist the dispatch into oshi.util.LogUtil and have both delegate. ExceptionUtil.logAtLevel keeps its signature, so oshi-core-ffm and any downstream caller are unaffected. LogUtil.isEnabled restores the capability of Logger#isEnabledForLevel that #3432 had to drop for slf4j 1.x compatibility. That lets handleError keep skipping FormatUtil.formatError when the level is off, without reintroducing an inline switch to do it. handleError also double-formatted an already-formatted string: FormatUtil.formatError returns the output of String.format, and the result was passed through String.format again with no arguments. PerfCounterQueryHandler had the same copy-paste, fixed there as well; its isWarnEnabled guards are left alone, since both log at a level known at the call site and can check it directly. Widen the forbidden-apis ban from org.slf4j.event.Level to the whole org.slf4j.event package. slf4j-api 1.7.5 has no such package at all, so every type in it breaks the same hosts that motivated #3524 and #3525. The level switch now lives in oshi-common, where a cross-platform test covers all ten branches. Previously the only fully covered copy was in PerfDataUtil, reachable only on Windows CI.
oshi compiles against slf4j-api 2.x, and
ExceptionUtil,PerfDataUtil#handleError, andForeignFunctions#logThrowablecallLogger#atLevel/setCauseandisEnabledForLevel, which don't exist in slf4j-api 1.x. Consumers embedded in tooling that still pins an older slf4j-api 1.x on the runtime classpath — some Gradle and Maven versions, for example — hit a NoSuchMethodError.We currently use oshi for Gradle plugins / Maven extensions and want to support those older versions. I think the change is low-cost and allows using oshi in more situations.
This PR replaces those calls with a level-switch to the classic error/warn/info/debug/ trace methods, which are identical in 1.x and 2.x. Log output doesn't change: a trailing Throwable is still attached as the log event's cause via SLF4J's implicit-cause handling, and PerfDataUtil still skips formatting the error message when the level is disabled.
No change to the slf4j.version build dependency — this only drops the compile-time dependency on API introduced in 2.x. Though I am open to change the compile time API to slf4j 1.x to make sure this is not changed again incidentally.
Tested:
mvn testpasses in oshi-common and oshi-core. Verified the replacement call pattern compiles against both slf4j-api 1.7.36 and 2.0.18 and produces identical log output in both.Summary by CodeRabbit
atLevel/setCauseusage to classic SLF4J level-specific logging.