Skip to content

Next set of slog migration changes for MDM - #39981

Merged
getvictor merged 4 commits into
mainfrom
victor/38889-slog-mdm
Feb 19, 2026
Merged

Next set of slog migration changes for MDM#39981
getvictor merged 4 commits into
mainfrom
victor/38889-slog-mdm

Conversation

@getvictor

@getvictor getvictor commented Feb 17, 2026

Copy link
Copy Markdown
Member

Related issue: Resolves #38889

Incremental set of slog migration changes for MDM packages.

Checklist for submitter

  • Changes file added for user-visible changes in changes/, orbit/changes/ or ee/fleetd-chrome/changes.
    • already added in a previous PR

Testing

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

Summary by CodeRabbit

  • Refactor
    • Standardized logging to Go's structured slog across MDM (Apple, Windows), DEP/ABM flows, maintained app sync, and related tests—improving log consistency and contextual diagnostics without changing user-facing behavior.

@getvictor

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Feb 17, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

Copilot AI 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.

Pull request overview

This PR continues the ongoing slog migration effort (ADR-0008) by migrating MDM-related code from go-kit/log to slog. The changes maintain backward compatibility using the platform logging adapter while gradually converting internal functions to use slog directly.

Changes:

  • Migrated Windows MDM profile management, Microsoft MDM profile verification, and maintained apps sync functions from kitlog.Logger to *slog.Logger
  • Updated all MDM-related log calls to use slog's context-aware methods (DebugContext, InfoContext, ErrorContext)
  • Updated test code to use slog.New(slog.DiscardHandler) instead of log.NewNopLogger()

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
server/service/osquery_utils/queries.go Removed platformlogging wrapper when calling Microsoft MDM functions; now passes logger directly
server/service/microsoft_mdm_test.go Updated test logger instantiation to use slog.DiscardHandler
server/service/microsoft_mdm.go Changed ReconcileWindowsProfiles signature to accept *slog.Logger and migrated all log calls to context-aware slog methods
server/service/integration_mdm_test.go Added .SlogLogger() call when passing logger to ReconcileWindowsProfiles
server/service/integration_mdm_profiles_test.go Added .SlogLogger() call when passing logger to VerifyHostMDMProfiles
server/service/apple_mdm.go Added .SlogLogger() calls when passing logger to profile variable replacement functions
server/mdm/profiles/profile_variables.go Changed function signatures to accept *slog.Logger and migrated log calls to ErrorContext
server/mdm/microsoft/profile_verifier_test.go Updated test logger instantiation to use slog.DiscardHandler
server/mdm/microsoft/profile_verifier.go Changed function signatures to accept *slog.Logger and migrated all log calls to context-aware slog methods
server/mdm/maintainedapps/testing_utils.go Updated test logger instantiation to use slog.DiscardHandler
server/mdm/maintainedapps/sync.go Changed Refresh function signature to accept *slog.Logger
cmd/fleet/cron.go Added .SlogLogger() calls when passing logger to ReconcileWindowsProfiles and maintained_apps.Refresh

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

Comment thread server/service/microsoft_mdm.go
@coderabbitai

coderabbitai Bot commented Feb 17, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

This PR migrates logging across MDM, Apple/Microsoft MDM, DEP, and related service and test code from go-kit/log and platform-specific logging to Go's standard library slog. It updates many function signatures and struct fields to accept *slog.Logger, replaces level-based logging calls with slog context-aware methods, and changes call sites to pass logger.SlogLogger() or construct slog loggers in tests. Several adapter types (e.g., NanoDEPLogger) and DEP/DEP client/service constructors were updated to use *slog.Logger. No functional control-flow or public API semantics, beyond logger types, were altered.

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.23% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The pull request description is incomplete and lacks critical details required by the template. Several mandatory checklist items are not properly addressed. Complete the PR description by: (1) providing a clear Related issue reference (appears partially complete with #38889), (2) explicitly addressing all database migration requirements if applicable, (3) confirming fleetd/orbit/Fleet Desktop compatibility if relevant, (4) providing a detailed summary of the logging migration changes being made, and (5) clarifying testing coverage for the slog migration across all affected MDM packages.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The PR title "Next set of slog migration changes for MDM" accurately summarizes the primary change—continuing the slog migration focused on MDM components.
Linked Issues check ✅ Passed The code changes successfully implement the slog migration objectives by converting MDM-related functions and services to use *slog.Logger instead of kitlog.Logger or platform logging.
Out of Scope Changes check ✅ Passed All changes are directly aligned with the slog migration goal stated in issue #38889. The modifications consistently replace logging types and update function signatures across MDM components.

✏️ 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-slog-mdm

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.

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

🧹 Nitpick comments (1)
server/service/microsoft_mdm.go (1)

639-639: Consider using ErrorContext or WarnContext for profile build failures.

Lines 639 and 677 log "error building command from profile" at Info level. Since these represent actual errors that cause a profile to be silently skipped (via continue), WarnContext or ErrorContext would better reflect severity and make debugging easier in production.

This is a minor suggestion — the current level may be preserving the original behavior.

Also applies to: 677-677

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/service/microsoft_mdm.go` at line 639, In
isEligibleForWindowsMDMMigration, replace the Info-level logs that print "error
building command from profile" (and the corresponding InfoContext call at the
other occurrence) with a higher-severity log such as WarnContext or ErrorContext
so profile build failures are surfaced (e.g., change logger.InfoContext(...,
"error building command from profile", ...) to logger.WarnContext or
logger.ErrorContext for that message); keep the same context fields so callers
can identify the profile/host but escalate the log level to reflect that the
profile was skipped due to an error.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@server/mdm/maintainedapps/testing_utils.go`:
- Around line 104-132: The test is creating a logger with
slog.New(slog.DiscardHandler) which is incompatible; update every call that
passes slog.New(slog.DiscardHandler) (e.g., in calls to Refresh in
testing_utils.go and related tests) to construct a compatible discard logger by
creating a handler that accepts an io.Writer (for example, use a text or JSON
handler targeting io.Discard) and pass slog.New(...) that handler instead, and
add the necessary import for io.

In `@server/service/microsoft_mdm_test.go`:
- Around line 768-775: The test
TestReconcileWindowsProfileWithCertificateFailureDoesNotAddManagedCertificate
constructs a logger using slog.DiscardHandler which can be incompatible; replace
that instantiation with a compatible handler (e.g., create the logger via
slog.New with slog.NewTextHandler or slog.NewJSONHandler targeting io.Discard
and an appropriate slog.HandlerOptions) and update imports accordingly so the
test uses a compatible discard handler instead of slog.DiscardHandler.
- Around line 712-715: Replace the incompatible use of slog.DiscardHandler when
creating logger in the test: instead of slog.New(slog.DiscardHandler) construct
a compatible discard handler (e.g., slog.NewTextHandler(io.Discard,
&slog.HandlerOptions{}) or slog.NewJSONHandler(io.Discard,
&slog.HandlerOptions{})) and pass that to slog.New; update the logger
initialization (logger := slog.New(...)) in the test where ctx and ds are set
(the lines with ctx := context.Background(), ds := new(mock.Store), logger :=
slog.New(...)) so the test uses a supported handler rather than
slog.DiscardHandler.
- Around line 833-840:
TestReconcileWindowsProfilesWithOneHostFailingStillAddsManagedCertificate uses
slog.New(slog.DiscardHandler) which may not be available across Go versions;
replace the DiscardHandler usage in that test by creating a logger with
slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{})) (ensure io is
imported) so the test uses a compatible discard sink instead of
slog.DiscardHandler.

---

Nitpick comments:
In `@server/service/microsoft_mdm.go`:
- Line 639: In isEligibleForWindowsMDMMigration, replace the Info-level logs
that print "error building command from profile" (and the corresponding
InfoContext call at the other occurrence) with a higher-severity log such as
WarnContext or ErrorContext so profile build failures are surfaced (e.g., change
logger.InfoContext(..., "error building command from profile", ...) to
logger.WarnContext or logger.ErrorContext for that message); keep the same
context fields so callers can identify the profile/host but escalate the log
level to reflect that the profile was skipped due to an error.

@codecov

codecov Bot commented Feb 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 66.19718% with 24 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.30%. Comparing base (39b0d5b) to head (b7ef410).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
server/mdm/apple/apple_mdm.go 72.22% 10 Missing ⚠️
cmd/fleet/cron.go 12.50% 6 Missing and 1 partial ⚠️
server/service/microsoft_mdm.go 50.00% 3 Missing ⚠️
ee/server/service/mdm.go 0.00% 1 Missing and 1 partial ⚠️
server/mdm/microsoft/profile_verifier.go 66.66% 1 Missing ⚠️
server/service/apple_mdm.go 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #39981      +/-   ##
==========================================
+ Coverage   66.29%   66.30%   +0.01%     
==========================================
  Files        2446     2444       -2     
  Lines      196006   195794     -212     
  Branches     8574     8444     -130     
==========================================
- Hits       129942   129830     -112     
+ Misses      54297    54197     -100     
  Partials    11767    11767              
Flag Coverage Δ
backend 68.09% <66.19%> (-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

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Feb 17, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

Copilot AI 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.

Pull request overview

Copilot reviewed 22 out of 22 changed files in this pull request and generated no new comments.


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

@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

🧹 Nitpick comments (3)
server/mdm/maintainedapps/sync.go (1)

36-43: Unused logger parameter in Refresh.

The logger parameter is accepted but never referenced in the function body. If this is a preparatory signature change for Phase 2, consider adding a brief comment or using _ = logger to signal intent and silence potential linter warnings.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/mdm/maintainedapps/sync.go` around lines 36 - 43, The Refresh function
signature accepts a logger (*slog.Logger) but never uses it, causing a linter
warning; either reference it or explicitly ignore it to signal intent. Update
Refresh (function Refresh) to use the logger for relevant log events (e.g., log
start, FetchAppsList error, or upsert result) or, if no logging is needed yet,
add a deliberate ignore like `_ = logger` or a brief comment noting it's
reserved for Phase 2 to silence linters; ensure the change is limited to the
Refresh function signature/body so callers remain unchanged.
server/service/apple_mdm.go (1)

5637-5656: Hoist SlogLogger() once per function for clarity.

Since this path can run inside variable-processing loops, consider caching the slog logger once and reusing it.

Suggested diff
 func preprocessProfileContents(
 	ctx context.Context,
 	appConfig *fleet.AppConfig,
 	ds fleet.Datastore,
 	scepConfig fleet.SCEPConfigService,
 	digiCertService fleet.DigiCertService,
 	logger *platformlogging.Logger,
@@
 ) error {
+	slogLogger := logger.SlogLogger()
 	// This method replaces Fleet variables ($FLEET_VAR_<NAME>) in the profile
 	// contents, generating a unique profile for each host. For a 2KB profile and
 	// 30K hosts, this method may generate ~60MB of profile data in memory.
@@
-				replacedContents, replacedVariable, err := profiles.ReplaceCustomSCEPChallengeVariable(ctx, logger.SlogLogger(), fleetVar, customSCEPCAs, hostContents)
+				replacedContents, replacedVariable, err := profiles.ReplaceCustomSCEPChallengeVariable(ctx, slogLogger, fleetVar, customSCEPCAs, hostContents)
@@
-				replacedContents, managedCertificate, replacedVariable, err := profiles.ReplaceCustomSCEPProxyURLVariable(ctx, logger.SlogLogger(), ds, appConfig, fleetVar, customSCEPCAs, hostContents, hostUUID, profUUID)
+				replacedContents, managedCertificate, replacedVariable, err := profiles.ReplaceCustomSCEPProxyURLVariable(ctx, slogLogger, ds, appConfig, fleetVar, customSCEPCAs, hostContents, hostUUID, profUUID)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/service/apple_mdm.go` around lines 5637 - 5656, Hoist
logger.SlogLogger() to a single local variable at the top of the function and
use that variable in the calls to profiles.ReplaceCustomSCEPChallengeVariable
and profiles.ReplaceCustomSCEPProxyURLVariable (and any other places inside the
variable-processing loop) instead of calling logger.SlogLogger() repeatedly;
update the callsites to pass the cached slogLogger variable and leave the rest
of the logic (hostContents updates and appending to managedCertificatePayloads)
unchanged.
server/mdm/apple/apple_mdm.go (1)

901-905: Type []any for slog attrs is fine but logCountsForResults still returns []interface{}.

The helper logCountsForResults (line 947) returns []interface{} while the local attrs is declared as []any. These are identical in Go, so no issue, but consider updating logCountsForResults to return []any for consistency with the modern style used here.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/mdm/apple/apple_mdm.go` around lines 901 - 905, Change the return type
of the helper logCountsForResults from []interface{} to []any so it matches the
local attrs declaration (attrs := []any{...}) and modern Go styles; update the
function signature for logCountsForResults and any callers to use []any and
adjust any internal variables to the any alias where needed to keep types
consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@server/mdm/apple/apple_mdm.go`:
- Around line 894-899: The log message is contradictory because it reports "no
error was returned" while the condition currently checks err != nil; update the
conditional in apple_mdm.go to check err == nil (i.e., replace the err != nil
check with err == nil) so the block that calls logger.ErrorContext(ctx, "assign
profile: no error was returned but some devices were not assigned a status in
the response", "devices", implicitlyFailedAssignments) only runs when there
truly is no error and implicitlyFailedAssignments > 0; alternatively, if the
original intent was to log when an error exists, change the log text to reflect
the presence of err and include err in the ErrorContext call—adjust the
condition and message around the implicitlyFailedAssignments/err check
accordingly.

---

Nitpick comments:
In `@server/mdm/apple/apple_mdm.go`:
- Around line 901-905: Change the return type of the helper logCountsForResults
from []interface{} to []any so it matches the local attrs declaration (attrs :=
[]any{...}) and modern Go styles; update the function signature for
logCountsForResults and any callers to use []any and adjust any internal
variables to the any alias where needed to keep types consistent.

In `@server/mdm/maintainedapps/sync.go`:
- Around line 36-43: The Refresh function signature accepts a logger
(*slog.Logger) but never uses it, causing a linter warning; either reference it
or explicitly ignore it to signal intent. Update Refresh (function Refresh) to
use the logger for relevant log events (e.g., log start, FetchAppsList error, or
upsert result) or, if no logging is needed yet, add a deliberate ignore like `_
= logger` or a brief comment noting it's reserved for Phase 2 to silence
linters; ensure the change is limited to the Refresh function signature/body so
callers remain unchanged.

In `@server/service/apple_mdm.go`:
- Around line 5637-5656: Hoist logger.SlogLogger() to a single local variable at
the top of the function and use that variable in the calls to
profiles.ReplaceCustomSCEPChallengeVariable and
profiles.ReplaceCustomSCEPProxyURLVariable (and any other places inside the
variable-processing loop) instead of calling logger.SlogLogger() repeatedly;
update the callsites to pass the cached slogLogger variable and leave the rest
of the logic (hostContents updates and appending to managedCertificatePayloads)
unchanged.

Comment thread server/mdm/apple/apple_mdm.go
@getvictor
getvictor marked this pull request as ready for review February 17, 2026 20:35
@getvictor
getvictor requested a review from a team as a code owner February 17, 2026 20:35
@getvictor
getvictor merged commit 4236363 into main Feb 19, 2026
40 checks passed
@getvictor
getvictor deleted the victor/38889-slog-mdm branch February 19, 2026 17:40
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 (1)

3 participants