Skip to content

Add errorprone-slf4j checks and fix the SLF4J misuse they found - #3610

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:errorprone-slf4j
Aug 14, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:errorprone-slf4j

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

Adds the errorprone-slf4j plugin (jp.skypencil.errorprone.slf4j, Apache-2.0) to the error-prone profile, and fixes everything it found except one deferred category.

It registers itself through META-INF/services, so it only needs to be on the annotationProcessorPath; its checks are then configured with -Xep like any core check. It declares error_prone_check_api as compileOnly, so it contributes no transitive dependency, and it is build-time only — nothing ships.

Check configuration

Check Setting Why
Slf4jPlaceholderMismatch ERROR 13 findings, fixed below
Slf4jFormatShouldBeConst ERROR 12 findings, fixed below
Slf4jLoggerShouldBePrivate ERROR zero findings — regression guard
Slf4jLoggerShouldBeFinal ERROR zero findings — regression guard
Slf4jIllegalPassedClass ERROR zero findings — regression guard
Slf4jDoNotLogMessageOfExceptionExplicitly WARN 74-site backlog, deferred to a follow-up
Slf4jLoggerShouldBeNonStatic OFF fires on all ~200 private static final Logger LOG fields
Slf4jSignOnlyFormat OFF only flagged the horizontal-rule separators the SystemInfoTest mains print

The three escalated-to-ERROR guards follow the same per-check pattern as #3606. Note the severity token Error Prone accepts is WARN, not WARNING.

Slf4jPlaceholderMismatch — 13 sites, one constant

ParseUtil.DEFAULT_LOG_MSG was \"{} didn't parse. Returning default. {}\", with the exception passed as the second argument. SLF4J trims a trailing Throwable out of the substitution arguments unconditionally, regardless of placeholder count, so the exception was attached as the event's cause (stack trace and all) while the second placeholder was emitted literally:

message  : abc didn't parse. Returning default. {}
throwable: NumberFormatException (stack trace printed)

Verified directly against slf4j-api 1.7.36 and 2.0.18. Dropping the placeholder leaves throwable handling exactly as it was and removes the stray {} from all 13 call sites, which are otherwise untouched.

Slf4jFormatShouldBeConst — 12 sites

  • MacInstalledApps (×2) concatenated e.getMessage() into the message and passed the exception, duplicating the text alongside the stack trace.
  • SmcUtil wrapped the entire message in String.format for a single %08x field. The constant is now the format string and only the hex value is formatted.
  • WmiQueryHandler and its FFM twin built the format in a local. Hoisted to a constant and expanded the Object[] into varargs — with the format resolvable, Slf4jPlaceholderMismatch cannot count elements of an Object[] variable, so keeping the array just trades one finding for another. Making the arguments explicit also exposed four DoNotLogMessageOfExceptionExplicitly sites the check could not see through the array, including the JNA twin's, which had been invisible while the FFM twin's were reported — hence 74 deferred sites rather than 70.
  • LogUtil.logAtLevel forwards a caller-supplied message by design, so it carries @SuppressWarnings rather than a fix.

Deferred to a follow-up

Slf4jDoNotLogMessageOfExceptionExplicitly, 74 sites across 44 files, sits at WARN so the backlog stays visible without blocking. Passing the throwable instead of e.getMessage() keeps the stack trace and cause chain, is null-safe (a bare new IOException() currently logs the literal null), and is cheaper when the level is disabled, since getMessage() is evaluated at the call site regardless. But it changes log output on every platform and the JNA/FFM twins have to move together, so it belongs in its own change. That check escalates to ERROR once drained.

Verification

  • ./mvnw clean spotless:apply sortpom:sort checkstyle:check install forbiddenapis:check javadoc:javadoc — clean, 1559 tests successful, 0 failed (macOS/aarch64/JDK 26).
  • ./mvnw clean install -DskipTests -Perror-prone — green, with only the deferred check's WARNING-severity findings and no other Error Prone output.
  • Full Linux CI green on my fork, including the Error Prone and SLF4J-1.7 lint jobs: dbwiddis/oshi/actions/runs/31820498107.

No CHANGELOG.md entry: this is build tooling plus log-message hygiene, with no API or behavior change.

Summary by CodeRabbit

  • Bug Fixes

    • Improved diagnostic logging for application discovery, parsing, hardware monitoring, and Windows system queries.
    • Preserved clearer exception details and appropriate warning or debug severity across platform-specific operations.
  • Chores

    • Added automated checks to help maintain consistent and reliable logging practices.

Adds the errorprone-slf4j plugin (jp.skypencil.errorprone.slf4j) to the
error-prone profile's annotationProcessorPath. It registers itself via
META-INF/services, so no -Xplugin change is needed; its checks are then
configured with -Xep like any core check. It declares error_prone_check_api
compileOnly, so it adds no transitive dependency, and is verified working
against error-prone 2.50.0 despite being built against an older API.

Two checks are OFF as findings the project rejects rather than a backlog:
Slf4jLoggerShouldBeNonStatic fires on all ~200 `private static final Logger
LOG` fields, whose staticness is deliberate, and Slf4jSignOnlyFormat only
flagged the horizontal-rule separator lines the SystemInfoTest mains print.

Slf4jDoNotLogMessageOfExceptionExplicitly is demoted to WARN: its 74-site
backlog is one the project intends to drain, but the fixes change log output
on every platform and belong in their own change. WARN keeps it visible
without blocking; it escalates to ERROR once drained. The remaining checks are
ERROR, three of them (LoggerShouldBePrivate, LoggerShouldBeFinal,
IllegalPassedClass) as pure regression guards since their backlog was zero.

Fixes for the ERROR-severity findings:

Slf4jPlaceholderMismatch (13 sites, one constant): ParseUtil's DEFAULT_LOG_MSG
had a trailing "{}" for the exception, but SLF4J unconditionally trims a
trailing Throwable out of the substitution arguments, so it was attached as the
event cause (with stack trace) while the second placeholder was emitted
literally. Verified against slf4j-api 1.7.36 and 2.0.18. Dropping the
placeholder leaves throwable handling unchanged and removes the stray "{}".

Slf4jFormatShouldBeConst (12 sites):
- MacInstalledApps concatenated e.getMessage() into the message *and* passed
  the exception, duplicating the text alongside the stack trace.
- SmcUtil wrapped the whole message in String.format for one hex field; the
  constant is now the format string and only the hex is formatted.
- WmiQueryHandler and its FFM twin built the format in a local. Hoisted to a
  constant and expanded the Object[] into varargs, because with the format
  resolvable Slf4jPlaceholderMismatch cannot count elements of an Object[]
  variable and the array form just trades one finding for another. Making the
  arguments explicit also exposed four DoNotLogMessageOfExceptionExplicitly
  sites the check could not see through the array - including the JNA twin's,
  which had been invisible while the FFM twin's were reported.
- LogUtil.logAtLevel forwards a caller-supplied message by design, so it is
  suppressed rather than fixed.
@coderabbitai

coderabbitai Bot commented Aug 14, 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 Plus

Run ID: 9e323b57-4ce8-45ad-93de-5014ffe37f89

📥 Commits

Reviewing files that changed from the base of the PR and between 754f001 and f22c049.

📒 Files selected for processing (7)
  • oshi-common/src/main/java/oshi/software/common/os/mac/MacInstalledApps.java
  • oshi-common/src/main/java/oshi/util/LogUtil.java
  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/WmiQueryHandlerFFM.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java
  • pom.xml
📜 Recent review details
⏰ Context from checks skipped due to timeout. (12)
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Error Prone
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Lint (ForbiddenAPIs, Javadoc, SLF4J)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{java,properties}

📄 CodeRabbit inference engine (AGENTS.md)

Before writing any parsing helper, check whether ParseUtil already has one.

Files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-common/src/main/java/oshi/software/common/os/mac/MacInstalledApps.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/WmiQueryHandlerFFM.java
  • oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java
  • oshi-common/src/main/java/oshi/util/LogUtil.java
oshi-common/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

oshi-common/**/*.java: oshi-common may not reference com.sun.jna.**, java.lang.foreign.**, or any
System.load/loadLibrary. It must stay pure JDK.

Files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-common/src/main/java/oshi/software/common/os/mac/MacInstalledApps.java
  • oshi-common/src/main/java/oshi/util/LogUtil.java
**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

**/*.java: Every public and protected type and method needs javadoc.
Do not use fully-qualified class names in
code or in javadoc — including inside {@link ...}. Import the type and link the simple name.
New files get a current-year-only
header (Copyright 2026 The OSHI Project Contributors / SPDX-License-Identifier: MIT), even when
copied from an older file; spotless maintains end years on existing files.
Never add a line range to
config/checkstyle-suppressions.xml — a range breaks the moment anything above it shifts, including a
single added import, and the failure looks unrelated to the change that caused it.
new classes are
expected to declare one, and matching the annotation of the class you are modeling yours on is the
right default.
Values that are constant (CPU model,
serial number) or expensive-but-slow-changing are wrapped in
oshi.util.Memoizer.memoize(supplier, ...)

Files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-common/src/main/java/oshi/software/common/os/mac/MacInstalledApps.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/WmiQueryHandlerFFM.java
  • oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java
  • oshi-common/src/main/java/oshi/util/LogUtil.java
oshi-core-ffm/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

oshi-core-ffm may not reference com.sun.jna.**.

Files:

  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/WmiQueryHandlerFFM.java
🧠 Learnings (5)
📚 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/ParseUtil.java
  • oshi-common/src/main/java/oshi/software/common/os/mac/MacInstalledApps.java
  • oshi-common/src/main/java/oshi/util/LogUtil.java
📚 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-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-common/src/main/java/oshi/software/common/os/mac/MacInstalledApps.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/WmiQueryHandlerFFM.java
  • oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java
  • oshi-common/src/main/java/oshi/util/LogUtil.java
📚 Learning: 2026-07-30T00:35:22.638Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3547
File: oshi-common/src/main/java/oshi/hardware/common/platform/unix/BsdFirmware.java:82-82
Timestamp: 2026-07-30T00:35:22.638Z
Learning: In OSHI, treat changes as “API-breaking” only when they affect classes (or relevant API surface) annotated with `PublicAPI`. Public classes/members that are not annotated with `PublicAPI` should be reviewed as internal implementation details, even if they are public (e.g., classes like `oshi.hardware.common.platform.unix.BsdFirmware`). Also, respect intentional visibility decisions used for tests—e.g., methods like `BsdFirmware.parseDmesg(List<String>)` may be intentionally package-private to support tests within the same package; avoid widening visibility or altering signatures unless the related `PublicAPI` contract requires it.

Applied to files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-common/src/main/java/oshi/software/common/os/mac/MacInstalledApps.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/WmiQueryHandlerFFM.java
  • oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java
  • oshi-common/src/main/java/oshi/util/LogUtil.java
📚 Learning: 2026-08-03T00:46:14.953Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3566
File: oshi-common/src/main/java/oshi/software/common/os/unix/openbsd/OpenBsdNetworkParams.java:18-22
Timestamp: 2026-08-03T00:46:14.953Z
Learning: In the OSHI Java codebase, do not require duplicate Javadoc on public methods annotated with Override when the inherited Javadoc from the parent declaration adequately documents the method. The general public-member Javadoc requirement should not flag these overrides solely because they lack redundant documentation.

Applied to files:

  • oshi-common/src/main/java/oshi/util/ParseUtil.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-common/src/main/java/oshi/software/common/os/mac/MacInstalledApps.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/WmiQueryHandlerFFM.java
  • oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java
  • oshi-common/src/main/java/oshi/util/LogUtil.java
📚 Learning: 2026-08-02T23:56:23.866Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3565
File: oshi-core-ffm/src/main/java/oshi/ffm/platform/unix/PosixLibcFunctions.java:51-56
Timestamp: 2026-08-02T23:56:23.866Z
Learning: For Java FFM bindings in the oshi-core-ffm module, assume a 64-bit JVM and 64-bit operating system. Do not flag 32-bit native ABI or memory-layout compatibility concerns, consistent with the project's JDK 25 support policy, unless that policy changes.

Applied to files:

  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/WmiQueryHandlerFFM.java
🔇 Additional comments (7)
pom.xml (1)

115-120: LGTM!

Also applies to: 1249-1283

oshi-common/src/main/java/oshi/util/LogUtil.java (1)

66-68: LGTM!

oshi-common/src/main/java/oshi/util/ParseUtil.java (1)

58-60: LGTM!

oshi-common/src/main/java/oshi/software/common/os/mac/MacInstalledApps.java (1)

103-110: LGTM!

oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java (1)

146-147: LGTM!

oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/WmiQueryHandlerFFM.java (1)

64-65: LGTM!

Also applies to: 425-429

oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java (1)

59-60: LGTM!

Also applies to: 207-212


📝 Walkthrough

Walkthrough

The change standardizes SLF4J logging across macOS and Windows code. It adds shared message formats, preserves existing log levels, corrects exception argument handling, and enables Error Prone SLF4J checks in Maven.

Changes

SLF4J logging standardization

Layer / File(s) Summary
SLF4J Error Prone checks
pom.xml
The Error Prone profile loads errorprone-slf4j and configures SLF4J check severities.
Shared logging formats and suppressions
oshi-common/src/main/java/oshi/util/LogUtil.java, oshi-common/src/main/java/oshi/util/ParseUtil.java
logAtLevel documents its dynamic format requirement. DEFAULT_LOG_MSG now supports a trailing exception argument.
Platform logging call sites
oshi-common/src/main/java/oshi/software/common/os/mac/MacInstalledApps.java, oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java, oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java, oshi-core-ffm/src/main/java/oshi/ffm/util/platform/windows/WmiQueryHandlerFFM.java
Logging calls pass values and exceptions as separate SLF4J arguments. Windows handlers share a COM exception format and retain their existing log levels.

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

Merge Risk: ⚪ Minimal · up to f22c0

This change adds build-time SLF4J checks and corrects the reported logging issues without changing shipped APIs or runtime behavior; no actionable merge-blocking risk remains after normal checks and review.

Poem

I’m a rabbit with logs in my den,
Now placeholders guide them again.
Exceptions hop free,
Formats stay tidy,
And Error Prone checks them at ten.

🚥 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 changes: adding error-prone-slf4j checks and fixing the detected SLF4J misuse.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

@codecov

codecov Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.80%. Comparing base (bff3925) to head (f22c049).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
.../oshi/software/common/os/mac/MacInstalledApps.java 0.00% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3610      +/-   ##
============================================
- Coverage     79.87%   79.80%   -0.08%     
- Complexity     3870     3993     +123     
============================================
  Files           696      696              
  Lines         24220    24220              
  Branches       4057     4057              
============================================
- Hits          19345    19328      -17     
- Misses         2712     2725      +13     
- Partials       2163     2167       +4     
Flag Coverage Δ
freebsd 33.52% <0.00%> (+<0.01%) ⬆️
linux 37.64% <0.00%> (+<0.01%) ⬆️
macos 38.45% <0.00%> (-0.04%) ⬇️
openbsd 32.70% <0.00%> (+<0.01%) ⬆️
solaris 34.19% <0.00%> (+0.02%) ⬆️
windows 45.28% <0.00%> (-0.03%) ⬇️

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.

@dbwiddis
dbwiddis merged commit 5ae99f4 into oshi:master Aug 14, 2026
19 checks passed
@dbwiddis
dbwiddis deleted the errorprone-slf4j branch August 14, 2026 17:00
dbwiddis added a commit that referenced this pull request Aug 14, 2026
…RROR (#3611)

The errorprone-slf4j check Slf4jDoNotLogMessageOfExceptionExplicitly was
adopted at WARN in #3610 with a 74-site backlog left to drain. This drains
it and moves the check to the plugin's default ERROR severity.

Every one of the 74 log statements substituted the exception's message into
the log text instead of passing the exception itself. Passing the throwable
is better on three counts: the stack trace and cause chain reach the logs
rather than a single message line; getMessage() returns null for exceptions
constructed without one, which logged the literal text "null"; and SLF4J
defers all rendering when the level is disabled, whereas getMessage() is
evaluated at the call site regardless.

Where the message ended in a placeholder that only existed to hold the
exception text, the placeholder is dropped along with any separator left
dangling in front of it. Three shared format constants (COM_EXCEPTION_MSG in
oshi-common, shared by both Sensors twins, and COM_EXCEPTION_FMT in each
WmiQueryHandler twin) lost their trailing placeholder instead, covering
eleven call sites between them.

AbstractNetworkIF built its InstantiationException from the SocketException's
message and discarded the exception, so the stack trace getNetworks() now
logs would have stopped there. It attaches the cause via initCause, since
InstantiationException has no (String, Throwable) constructor.

ExceptionUtil.logAtLevel appends both t.getMessage() and t to an Object[]
before dispatching, which these checks cannot see through, so its callers
are untouched here and left for a follow-up.
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.

1 participant