Skip to content

Avoid SLF4J 2-only Logger API in logging helpers - #3432

Merged
dbwiddis merged 8 commits into
oshi:masterfrom
wolfs:slf4j-1x-compatible-api
Jul 7, 2026
Merged

dbwiddis merged 8 commits into
oshi:masterfrom
wolfs:slf4j-1x-compatible-api

Conversation

@wolfs

@wolfs wolfs commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

oshi compiles against slf4j-api 2.x, and ExceptionUtil, PerfDataUtil#handleError, and ForeignFunctions#logThrowable call Logger#atLevel/setCause and isEnabledForLevel, 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 test passes 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

  • Bug Fixes
    • Improved exception, foreign-function, and Windows performance-data error logging consistency by switching from atLevel/setCause usage to classic SLF4J level-specific logging.
    • Added a shared helper to log exceptions reliably across all supported log levels.
  • Tests
    • Expanded unit coverage to verify default return behavior and error handling across every log level.
  • Chores / CI
    • Added a build check to compile against an older SLF4J API for compatibility.
  • Documentation
    • Updated the 7.4.0 (in progress) changelog with the logging compatibility improvements.

wolfs added 3 commits July 6, 2026 18:30
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.
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 25d2944c-9daa-468d-932d-0a917a360921

📥 Commits

Reviewing files that changed from the base of the PR and between 7c8556b and b76b31e.

📒 Files selected for processing (6)
  • .github/workflows/pr.yaml
  • oshi-common/src/main/java/oshi/util/ExceptionUtil.java
  • oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java
  • oshi-core-ffm/src/main/java/oshi/ffm/ForeignFunctions.java
  • oshi-core/src/test/java/oshi/util/platform/windows/PerfDataUtilTest.java
  • pom.xml
📜 Recent review details
⏰ Context from checks skipped due to timeout. (15)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2026-05-31T05:53:04.246Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3311
File: .github/workflows/site.yaml:21-21
Timestamp: 2026-05-31T05:53:04.246Z
Learning: When a GitHub Actions workflow verifies that a pinned commit SHA matches a version tag, dereference annotated tags before comparing to a commit SHA. The API `GET /repos/{owner}/{repo}/git/refs/tags/{tag}` returns the tag *object* SHA for annotated tags (not the underlying commit SHA), so comparing it directly to a commit SHA will cause false mismatches. Instead: (1) fetch the tag object SHA via `GET /repos/{owner}/{repo}/git/refs/tags/{tag}`; (2) resolve that tag object to the underlying commit by calling `GET /repos/{owner}/{repo}/git/tags/{tag_object_sha}`; (3) compare the pinned commit SHA to the resolved commit at `.object.sha`.

Applied to files:

  • .github/workflows/pr.yaml
📚 Learning: 2026-07-06T19:25:59.225Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3432
File: oshi-common/src/main/java/oshi/util/ExceptionUtil.java:26-56
Timestamp: 2026-07-06T19:25:59.225Z
Learning: In this repo’s SLF4J 1.x-compatible logging code, do not flag cases where a logger call uses SLF4J 1.6+ implicit-cause handling—e.g., `log.error("...{}", value, t)` (or similar with a single `{}` placeholder) where `t` is passed as the final/trailing argument. SLF4J will attach `t` as the log event’s cause with the full stack trace; this is equivalent to SLF4J 2.x’s fluent `atLevel(...).setCause(t).log(...)` and is intentionally used to preserve SLF4J 1.x runtime compatibility.

Applied to files:

  • oshi-core-ffm/src/main/java/oshi/ffm/ForeignFunctions.java
  • oshi-common/src/main/java/oshi/util/ExceptionUtil.java
📚 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 (8)
pom.xml (2)

89-89: Unchanged in this diff; the org.slf4j.event OSGi import range is already widened to [1.7,3.0), matching the requested follow-up.


1139-1148: LGTM! Implements the requested verify-slf4j-17 profile to catch future SLF4J 2.0-only API usage at compile time, without altering the default slf4j.version used at runtime/test.

oshi-common/src/main/java/oshi/util/ExceptionUtil.java (2)

26-58: Correct SLF4J 1.x-compatible cause handling; public visibility change is justified.

The log.error(msg, t.getMessage(), t) pattern with a single {} placeholder relies on SLF4J's implicit-cause handling (since 1.6.0) to attach t as the log event's cause with full stack trace — functionally equivalent to the removed .setCause(t) fluent call, and correctly avoids SLF4J 2.x-only APIs. Making the method public is appropriate since ForeignFunctions#logThrowable now delegates to it.

Based on learnings, in this repo's SLF4J 1.x-compatible logging code, do not flag cases where a logger call uses SLF4J 1.6+ implicit-cause handling—e.g., log.error("...{}", value, t) (or similar with a single {} placeholder) where t is passed as the final/trailing argument.

Source: Learnings


192-192: LGTM!

Also applies to: 242-242, 292-292, 343-343, 394-394, 427-427, 459-459, 491-491, 532-532

oshi-core-ffm/src/main/java/oshi/ffm/ForeignFunctions.java (1)

25-26: Dedup follow-up correctly implemented.

logThrowable now delegates to the shared ExceptionUtil.logAtLevel, matching the requested consolidation. The message + ": {}" argument correctly supplies exactly one placeholder for t.getMessage() while keeping t trailing for implicit-cause attachment, consistent with the shared helper's contract.

Also applies to: 486-490

oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java (1)

384-393: LGTM! Satisfies the requested enum-coverage test for ExceptionUtil.

oshi-core/src/test/java/oshi/util/platform/windows/PerfDataUtilTest.java (1)

15-15: LGTM! Satisfies the requested enum-coverage test for PerfDataUtil.handleError.

Also applies to: 39-45

.github/workflows/pr.yaml (1)

41-42: LGTM! Adds the requested CI step compiling against SLF4J 1.7.36 to catch SLF4J 2.0-only API regressions.


📝 Walkthrough

Walkthrough

This PR replaces fluent SLF4J atLevel(...).setCause(...).log(...) calls with explicit level-specific logger methods in ExceptionUtil, ForeignFunctions, and PerfDataUtil. It adds tests, a Maven compatibility profile, a CI check, and a changelog note.

Changes

Level-based logging compatibility

Layer / File(s) Summary
Logging dispatch updates
oshi-common/src/main/java/oshi/util/ExceptionUtil.java, oshi-core-ffm/src/main/java/oshi/ffm/ForeignFunctions.java, oshi-core/src/main/java/oshi/util/platform/windows/PerfDataUtil.java
Adds ExceptionUtil.logAtLevel, updates its Level-based helper overloads to use it, and routes ForeignFunctions and PerfDataUtil logging through explicit SLF4J level methods.
Compatibility checks and notes
oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java, oshi-core/src/test/java/oshi/util/platform/windows/PerfDataUtilTest.java, pom.xml, .github/workflows/pr.yaml, CHANGELOG.md
Adds level-iteration tests, a verify-slf4j-17 Maven profile, a CI compile step for that profile, and a changelog entry for the logging API update.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • oshi/oshi#3272: Directly touches the same ExceptionUtil logging implementation and overloads that this PR modifies.
  • oshi/oshi#3355: Also modifies ExceptionUtil's exception-logging path for Level-based overloads.

Poem

A bunny hopped through logs so bright,
Each Level found its proper light.
Old fluent calls took one last bow,
Plain SLF4J says “hello” now.
🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: replacing SLF4J 2-only logging APIs in helper methods with compatible alternatives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@wolfs
wolfs marked this pull request as ready for review July 6, 2026 16:56
@codecov

codecov Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.87500% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.12%. Comparing base (0d7992f) to head (b76b31e).

Files with missing lines Patch % Lines
.../java/oshi/util/platform/windows/PerfDataUtil.java 25.00% 4 Missing and 5 partials ⚠️
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     
Flag Coverage Δ
freebsd 26.94% <62.50%> (+<0.01%) ⬆️
linux 31.54% <62.50%> (+0.02%) ⬆️
macos 31.77% <62.50%> (-0.02%) ⬇️
openbsd 26.43% <62.50%> (+0.02%) ⬆️
solaris 28.49% <62.50%> (+0.02%) ⬆️
windows 40.01% <71.87%> (-0.05%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0d7992f and 72e118f.

📒 Files selected for processing (3)
  • oshi-common/src/main/java/oshi/util/ExceptionUtil.java
  • oshi-core-ffm/src/main/java/oshi/ffm/ForeignFunctions.java
  • oshi-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!

@dbwiddis

dbwiddis commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

Thanks @wolfs!

I bumped into this in my earlier Sonar cleanup and thought I got all of them but obviously missed a few.

I think the change is low-cost and allows using oshi in more situations.

Agreed, OSHI's philosophy has always been to maximize compatibility.

A few requests before merge:

  1. I agree we should consider changing the compile time version to the latest 1.7, but I am leaning against it. Thoughts:
    • The primary reason for using 2.x was to put it on the module path. 1.7 does generate an Automatic Module Name but I'd prefer working with the latest version
    • We could alternately bring back animal-sniffer maven plugin but that's probably overkill.
    • Or we could add a test that reads the generated bnd manifests (but that's complexity we probably don't need.)
    • Perhaps we could have a test simulate the 1.7.x scenario to identify this failure during CI? Sample maven profile for the test, seemed to work for me (build failed on master, success on this PR):
<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
  1. If we don't change the compile time version, we should also widen the OSGi org.slf4j.event import range. Looking at the generated bundle manifests: this PR correctly drops org.slf4j.spi;[2.0,3) (the fluent LoggingEventBuilder), but org.slf4j.event;[2.0,3) remains. Level has existed since slf4j 1.7.15, so it's runtime-safe on 1.7, but an OSGi bundle would still resolve only against slf4j 2.x.
<osgi.slf4j.import.packages>org.slf4j;version="[1.7,3.0)",org.slf4j.event;version="[1.7,3.0)"</osgi.slf4j.import.packages>
  1. DRY. The ExceptionUtil.logAtLevel effectively duplicates code in ForeignFunctions.logThrowable. Since oshi-core-ffm depends on oshi-common, ForeignFunctions could call the new shared ExceptionUtil helper with the formatted message.

@dbwiddis

dbwiddis commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

One other request, add a test to validate we cover all the Level enum values:

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

wolfs added 4 commits July 7, 2026 07:59
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.
@dbwiddis

dbwiddis commented Jul 7, 2026

Copy link
Copy Markdown
Member

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
dbwiddis merged commit 6b0ab19 into oshi:master Jul 7, 2026
20 checks passed
@wolfs

wolfs commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

@dbwiddis Happy to help. Thank you for the quick turnaround! Do you already know when you'll cut a release including these new changes?

@dbwiddis

dbwiddis commented Jul 7, 2026

Copy link
Copy Markdown
Member

@wolfs Planning on this coming weekend. I've been traveling and need to get home to have a docked monitor for my laptop to finish #3404 implementation.

If there's an urgent earlier need I can cut a 7.3.3 patch release but if you can wait 5 days or so, 7.4.0 will be out.

@wolfs
wolfs deleted the slf4j-1x-compatible-api branch July 7, 2026 07:37
dbwiddis added a commit that referenced this pull request Jul 26, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants