Skip to content

Converted osquery_utils to slog#39883

Open
getvictor wants to merge 4 commits intomainfrom
victor/38889-osquery_utils-slog
Open

Converted osquery_utils to slog#39883
getvictor wants to merge 4 commits intomainfrom
victor/38889-osquery_utils-slog

Conversation

@getvictor
Copy link
Member

@getvictor getvictor commented Feb 13, 2026

Related issue: Resolves #38889

Plan was to convert osquery_utils package to slog. Picked up some additional code that was related.

Checklist for submitter

  • Changes file added for user-visible changes in changes/, orbit/changes/ or ee/fleetd-chrome/changes.
    • Already have changes

Testing

  • Added/updated automated tests
  • QA'd all new/changed functionality manually

Summary by CodeRabbit

Release Notes

Refactor

  • Updated internal logging infrastructure to use improved system-level logging utilities

Tests

  • Updated test suite to align with internal logging changes

Note: This release contains internal infrastructure improvements with no user-facing changes or new features.

@getvictor
Copy link
Member Author

@coderabbitai full review

@getvictor getvictor requested a review from Copilot February 13, 2026 23:51
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 13, 2026

✅ Actions performed

Full review triggered.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR continues the repository’s slog migration by updating osquery detail-query ingestion (and a maintained-apps validation CLI) to use log/slog instead of go-kit/log, and adjusts server/test call sites accordingly.

Changes:

  • Migrate osquery_utils DetailQuery hooks (QueryFunc/IngestFunc/Direct*IngestFunc) from log.Logger to *slog.Logger (with context-aware logging).
  • Update Fleet server/service code paths to pass svc.logger.SlogLogger() into osquery ingestion and preprocessing.
  • Update unit/integration tests and the cmd/maintained-apps/validate tool to use slog-based loggers.

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
server/service/osquery_utils/queries.go Converts detail query hooks + many ingest functions to *slog.Logger and updates logging calls.
server/service/osquery_utils/queries_test.go Updates tests to use t.Context() and slog discard/text handlers.
server/service/osquery_utils/disk_encryption_helpers.go Migrates helper to accept *slog.Logger and use DebugContext.
server/service/osquery_utils/disk_encryption_helpers_test.go Updates tests to pass slog discard logger.
server/service/osquery.go Passes svc.logger.SlogLogger() into osquery detail query ingestion and adds ctx to preprocessing helpers.
server/service/osquery_test.go Updates tests/bench to call preprocessing with ctx + slog discard logger.
server/service/orbit.go Updates disk encryption helper call sites to pass svc.logger.SlogLogger().
server/service/integration_core_test.go Updates ingest tests to use slog JSON handler log capture and adjusts assertions.
server/service/integration_mdm_test.go Replaces nop logger with slog discard logger in detail query ingest calls.
server/service/integration_enterprise_test.go Replaces nop logger with slog discard logger in detail query ingest calls.
cmd/maintained-apps/validate/main.go Migrates CLI logger to slog and updates logging calls throughout validation flow.
cmd/maintained-apps/validate/darwin.go Migrates validate helpers to slog (InfoContext/etc.) and updates MutateSoftwareOnIngestion call.
cmd/maintained-apps/validate/windows.go Migrates validate helpers to slog (InfoContext/etc.) and updates MutateSoftwareOnIngestion call.
cmd/maintained-apps/validate/app_commander.go Migrates commander logging to slog and threads ctx into filesystem-change detection logs.
cmd/maintained-apps/validate/app_commander_test.go Updates tests to pass ctx and use slog discard loggers.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 13, 2026

Walkthrough

This PR migrates the codebase from go-kit/log to Go's standard slog package. Changes include replacing logger type declarations from kitlog.Logger to *slog.Logger, updating function signatures to accept context parameters for context-aware logging, replacing logging calls with slog's context methods (InfoContext, ErrorContext, WarnContext, DebugContext), and updating imports and logger initialization. The migration affects the cmd/maintained-apps/validate package, server service layer, osquery utilities, and disk encryption helpers across multiple files.

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 3
❌ Failed checks (3 warnings)
Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes changes beyond osquery_utils (app_commander, darwin, windows, main.go, integration tests, and orbit.go). While these are logging migrations related to the slog effort, they extend beyond the stated scope of converting osquery_utils. Clarify in the PR description why related files were modified together and whether they are necessary for osquery_utils migration completion, or consider splitting into a focused PR.
Docstring Coverage ⚠️ Warning Docstring coverage is 18.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Merge Conflict Detection ⚠️ Warning ❌ Merge conflicts detected (38 files):

⚔️ cmd/fleetctl/fleetctl/gitops_test.go (content)
⚔️ cmd/fleetctl/fleetctl/testing_utils/testing_utils.go (content)
⚔️ cmd/fleetctl/integrationtest/gitops/gitops_enterprise_integration_test.go (content)
⚔️ cmd/fleetctl/integrationtest/gitops/software_test.go (content)
⚔️ cmd/maintained-apps/validate/app_commander.go (content)
⚔️ cmd/maintained-apps/validate/app_commander_test.go (content)
⚔️ cmd/maintained-apps/validate/darwin.go (content)
⚔️ cmd/maintained-apps/validate/main.go (content)
⚔️ cmd/maintained-apps/validate/windows.go (content)
⚔️ docs/REST API/rest-api.md (content)
⚔️ ee/server/service/software_installers.go (content)
⚔️ ee/server/service/vpp.go (content)
⚔️ ee/server/service/vpp_test.go (content)
⚔️ frontend/pages/hosts/ManageHostsPage/HostTableConfig.tsx (content)
⚔️ frontend/pages/hosts/ManageHostsPage/ManageHostsPage.tsx (content)
⚔️ frontend/pages/hosts/ManageHostsPage/components/LabelFilterSelect/LabelFilterSelect.tsx (content)
⚔️ frontend/pages/hosts/details/HostDetailsPage/HostDetailsPage.tsx (content)
⚔️ frontend/pages/hosts/details/HostQueryReport/HostQueryReport.tsx (content)
⚔️ frontend/pages/hosts/details/cards/HostSoftwareLibrary/HostSoftwareLibrary.tsx (content)
⚔️ frontend/pages/hosts/details/cards/HostSoftwareLibrary/HostSoftwareLibraryTable/HostSoftwareLibraryTable.tsx (content)
⚔️ frontend/pages/hosts/details/cards/Software/HostSoftware.tsx (content)
⚔️ frontend/pages/hosts/details/cards/Software/HostSoftwareTable/HostSoftwareTable.tsx (content)
⚔️ frontend/pages/queries/details/QueryDetailsPage/QueryDetailsPage.tsx (content)
⚔️ frontend/pages/queries/edit/EditQueryPage.tsx (content)
⚔️ frontend/router/paths.ts (content)
⚔️ frontend/styles/global/_global.scss (content)
⚔️ handbook/ceo/README.md (content)
⚔️ server/datastore/mysql/mysql_test.go (content)
⚔️ server/service/integration_core_test.go (content)
⚔️ server/service/integration_enterprise_test.go (content)
⚔️ server/service/integration_mdm_test.go (content)
⚔️ server/service/orbit.go (content)
⚔️ server/service/osquery.go (content)
⚔️ server/service/osquery_test.go (content)
⚔️ server/service/osquery_utils/disk_encryption_helpers.go (content)
⚔️ server/service/osquery_utils/disk_encryption_helpers_test.go (content)
⚔️ server/service/osquery_utils/queries.go (content)
⚔️ server/service/osquery_utils/queries_test.go (content)

These conflicts must be resolved before merging into main.
Resolve conflicts locally and push changes to this branch.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Converted osquery_utils to slog' is clear and specific, directly describing the main change that converts the osquery_utils package to use slog-based logging.
Description check ✅ Passed The PR description includes the related issue (#38889), testing confirmation, and explicitly mentions related code was picked up. However, some template items like 'Changes file added' are unchecked and several critical sections lack detail on implementation approach.
Linked Issues check ✅ Passed The PR successfully migrates osquery_utils and related services to slog-based logging with context propagation, aligning with issue #38889 Phase 1 goals of establishing a slog foundation while maintaining backward compatibility.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch victor/38889-osquery_utils-slog
⚔️ Resolve merge conflicts (beta)
  • Auto-commit resolved conflicts to branch victor/38889-osquery_utils-slog
  • Create stacked PR with resolved conflicts
  • Post resolved changes as copyable diffs in a comment

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 and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@cmd/maintained-apps/validate/main.go`:
- Line 166: The call to appExists is passing cfg.logger instead of the per-app
logger appLogger, which strips the `"app"` context from logs; update the
invocation of appExists to pass appLogger (the logger with the `"app"` key
attached) so all logs inside appExists retain per-app context—i.e., replace the
cfg.logger argument with appLogger in the appExists(...) call that currently
uses ac.Name, ac.UniqueIdentifier, ac.Version, ac.AppPath.

In `@server/service/osquery_utils/queries_test.go`:
- Around line 56-57: The test calls MutateSoftwareOnIngestion with dcvViewer
instead of the intended noOp, so the noOp object is never mutated and the
assertion on noOp.Version is meaningless; change the call to
MutateSoftwareOnIngestion(t.Context(), noOp, slog.New(slog.DiscardHandler)) so
the no-op case is exercised and the subsequent assert.Equal(t, "2024",
noOp.Version) actually validates the no-op behavior for the noOp variable.

In `@server/service/osquery_utils/queries.go`:
- Line 2906: Replace the empty message string in the logger.DebugContext calls
inside the luksVerifyQueryIngester code path with a concise, human-readable
message (e.g., "luksVerifyQueryIngester error" or similar) so the first slog
argument is meaningful; update both occurrences (the one shown with
"method","luksVerifyQueryIngester" and the other at the later call around line
2917) to include contextual text while keeping the existing structured fields
(component, method, host, err) unchanged.
🧹 Nitpick comments (8)
server/service/integration_mdm_test.go (1)

6148-6148: Repeated slog.New(slog.DiscardHandler) allocations across test call sites — acceptable but could be simplified.

Five call sites each allocate a new discard logger. For test code this is fine, but if you want to tidy it up, a single discardLogger local at the top of the test function would reduce noise.

Also applies to: 6179-6179, 6245-6245, 6492-6492, 6513-6513

cmd/maintained-apps/validate/darwin.go (1)

31-43: Prefer slog's native key-value args over fmt.Sprintf.

Using fmt.Sprintf inside slog.InfoContext collapses everything into an unstructured message string, which defeats slog's structured logging model. The same pattern appears throughout this file (lines 31, 37, 40–43, 193, 237, 243, 251, 260, 269).

With structured args, log aggregators can filter/index on individual fields, and the allocations from fmt.Sprintf are avoided when the log level is disabled.

Example refactor for this block
-	appLogger.InfoContext(ctx, fmt.Sprintf("Forcing LaunchServices refresh for: '%s'", appPath))
+	appLogger.InfoContext(ctx, "Forcing LaunchServices refresh", "appPath", appPath)
 	err := forceLaunchServicesRefresh(appPath)
 	if err != nil {
 		return fmt.Errorf("Error forcing LaunchServices refresh: %v. Attempting to continue", err)
 	}

-	appLogger.InfoContext(ctx, fmt.Sprintf("Attempting to remove quarantine for: '%s'", appPath))
+	appLogger.InfoContext(ctx, "Attempting to remove quarantine", "appPath", appPath)
 	quarantineResult, err := removeAppQuarantine(appPath)

-	appLogger.InfoContext(ctx, fmt.Sprintf("Quarantine output error: %v", quarantineResult.QuarantineOutputError))
-	appLogger.InfoContext(ctx, fmt.Sprintf("Quarantine status: %s", quarantineResult.QuarantineStatus))
-	appLogger.InfoContext(ctx, fmt.Sprintf("Spctl output error: %v", quarantineResult.SpctlOutputError))
-	appLogger.InfoContext(ctx, fmt.Sprintf("spctl status: %s", quarantineResult.SpctlStatus))
+	appLogger.InfoContext(ctx, "Quarantine removal result",
+		"quarantineOutputError", quarantineResult.QuarantineOutputError,
+		"quarantineStatus", quarantineResult.QuarantineStatus,
+		"spctlOutputError", quarantineResult.SpctlOutputError,
+		"spctlStatus", quarantineResult.SpctlStatus,
+	)

The same applies to all other fmt.Sprintf-wrapped calls in appExists (e.g., lines 193, 237, 243, 251, 260, 269).

server/service/osquery.go (1)

1570-1597: ErrorContext for a non-fatal extra-query failure may be too noisy — consider WarnContext.

Line 1591 uses logger.ErrorContext for a case where an extra software query returned errors, but execution continues normally. The previous go-kit code likely used a lower severity. slog.ErrorContext could trigger alerts in production log monitoring for what is essentially a degraded-but-not-broken path. WarnContext or DebugContext may be more appropriate here.

cmd/maintained-apps/validate/app_commander.go (1)

70-83: Consider using slog structured key-value pairs instead of fmt.Sprintf.

Throughout this file, log messages use fmt.Sprintf to format the message string. With slog, the idiomatic approach is to use structured key-value attributes, which enables better log parsing and filtering.

For example:

// Instead of:
ac.appLogger.InfoContext(ctx, fmt.Sprintf("New application detected at: %s", appPath))

// Prefer:
ac.appLogger.InfoContext(ctx, "new application detected", "path", appPath)

This applies to many call sites in this file (lines 70, 83, 88, 91–92, 95, 99, 103, 126, 129, 131). Not blocking, but worth adopting for new slog code.

Also applies to: 88-95, 99-103, 126-131

cmd/maintained-apps/validate/windows.go (1)

53-66: Same fmt.Sprintf note applies here.

Same optional refactor as in app_commander.go — prefer slog structured attributes over fmt.Sprintf in log messages for better queryability. For example:

// Instead of:
logger.InfoContext(ctx, fmt.Sprintf("Looking for app: %s, version: %s", appName, appVersion))

// Prefer:
logger.InfoContext(ctx, "looking for app", "app", appName, "version", appVersion)

Also applies to: 77-77, 92-92, 97-97, 151-151

cmd/maintained-apps/validate/main.go (1)

44-44: Consider using slog's structured key-value args instead of fmt.Sprintf.

Throughout this file, the pattern cfg.logger.ErrorContext(ctx, fmt.Sprintf("Error ...: %v", err)) bakes the error into the message string. slog is designed for structured logging — using cfg.logger.ErrorContext(ctx, "error getting list of apps", "error", err) makes errors filterable/indexable. This is a migration PR so deferring is fine, but it applies to nearly every log call here.

server/service/osquery_utils/queries.go (2)

204-208: Consider using structured key-value pairs instead of fmt.Sprintf for the slog message.

Throughout this file (~20 instances), dynamic values are embedded in the message via fmt.Sprintf. With slog, the idiomatic approach is a static message string plus structured key-value attributes, which improves log indexing and filtering. This is a pattern-level suggestion — not blocking.

Example for this location:

Illustrative refactor
-			logger.ErrorContext(ctx, fmt.Sprintf("detail_query_os_version expected single result got %d", len(rows)),
-				"component", "service", "method", "IngestFunc")
+			logger.ErrorContext(ctx, "detail_query_os_version unexpected result count",
+				"count", len(rows), "component", "service", "method", "IngestFunc")

2242-2257: Multiple defer registrations possible across the two sanitizer loops.

If a software entry matches both a basicAppSanitizers entry and a customAppSanitizers entry, two separate defer/recover closures are registered. This is pre-existing behavior (not introduced by this PR), but worth noting: the second defer's panic handler would capture s.Name/s.Version values already mutated by the first sanitizer. Not blocking.

@codecov
Copy link

codecov bot commented Feb 13, 2026

Codecov Report

❌ Patch coverage is 65.66265% with 57 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.27%. Comparing base (0ff707a) to head (6b67cd7).

Files with missing lines Patch % Lines
server/service/osquery_utils/queries.go 63.01% 54 Missing ⚠️
server/service/orbit.go 50.00% 0 Missing and 1 partial ⚠️
server/service/osquery.go 93.33% 1 Missing ⚠️
...r/service/osquery_utils/disk_encryption_helpers.go 66.66% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #39883   +/-   ##
=======================================
  Coverage   66.26%   66.27%           
=======================================
  Files        2439     2439           
  Lines      195437   195375   -62     
  Branches     8550     8550           
=======================================
- Hits       129512   129478   -34     
+ Misses      54197    54167   -30     
- Partials    11728    11730    +2     
Flag Coverage Δ
backend 68.07% <65.66%> (+<0.01%) ⬆️

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

☔ View full report in Codecov by Sentry.
📢 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@getvictor getvictor marked this pull request as ready for review February 14, 2026 02:14
@getvictor getvictor requested a review from a team as a code owner February 14, 2026 02:14
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.

slog migration

2 participants