Skip to content

slog migration: initLogger + serve.go + cron + schedule - #40699

Merged
getvictor merged 1 commit into
mainfrom
victor/40054-slog-initlogger
Feb 27, 2026
Merged

slog migration: initLogger + serve.go + cron + schedule#40699
getvictor merged 1 commit into
mainfrom
victor/40054-slog-initlogger

Conversation

@getvictor

@getvictor getvictor commented Feb 27, 2026

Copy link
Copy Markdown
Member

Related issue: Resolves #40540

Almost done with slog migration.

Checklist for submitter

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

Testing

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

Summary by CodeRabbit

  • Chores
    • Updated internal logging infrastructure to use Go's standard logging library, modernizing the logging system while maintaining existing functionality and error handling behavior.

@getvictor

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Feb 27, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@codecov

codecov Bot commented Feb 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 16.66667% with 160 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.28%. Comparing base (1a8662d) to head (2bd4dcd).
⚠️ Report is 31 commits behind head on main.

Files with missing lines Patch % Lines
cmd/fleet/serve.go 0.00% 107 Missing ⚠️
cmd/fleet/cron.go 20.00% 45 Missing and 3 partials ⚠️
cmd/fleet/main.go 0.00% 2 Missing ⚠️
cmd/fleet/vuln_process.go 66.66% 1 Missing ⚠️
server/datastore/mysql/sessions.go 0.00% 1 Missing ⚠️
server/service/schedule/schedule.go 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #40699      +/-   ##
==========================================
- Coverage   66.32%   66.28%   -0.05%     
==========================================
  Files        2466     2467       +1     
  Lines      196887   197496     +609     
  Branches     8618     8618              
==========================================
+ Hits       130594   130905     +311     
- Misses      54454    54736     +282     
- Partials    11839    11855      +16     
Flag Coverage Δ
backend 68.09% <16.66%> (-0.14%) ⬇️
backend-activity 88.61% <ø> (?)

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.

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 pull request continues the slog migration effort (part 2 of #38889) by migrating logging in core initialization, server startup, cron jobs, and scheduling infrastructure from the kitlog-based *logging.Logger wrapper to *slog.Logger directly.

Changes:

  • Updated initLogger to return *slog.Logger directly instead of wrapping it in *logging.Logger
  • Migrated serve.go logging calls from kitlog patterns to slog patterns (InfoContext, ErrorContext, etc.)
  • Updated all cron job and schedule functions to accept and use *slog.Logger
  • Added context parameter to TriggerFatalError and SetFatalErrorHandler for better error context propagation
  • Updated integration and unit tests to use slog logger initialization patterns

Reviewed changes

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

Show a summary per file
File Description
cmd/fleet/main.go Changed initLogger to return *slog.Logger directly instead of *logging.Logger
cmd/fleet/serve.go Migrated all logging calls from kitlog to slog patterns; removed .SlogLogger() calls
cmd/fleet/serve_test.go Updated test logger initialization to use slog.New(slog.DiscardHandler)
cmd/fleet/cron.go Updated all cron functions to accept *slog.Logger; removed .SlogLogger() adapter calls
cmd/fleet/cron_test.go Updated test logger initialization to use slog patterns
cmd/fleet/vuln_process.go Updated vulnerability processing functions to accept *slog.Logger
server/service/schedule/schedule.go Migrated Schedule type to use *slog.Logger; updated WithLogger option
server/service/integration_mdm_test.go Updated test schedule creation to use *slog.Logger directly
server/service/integration_enterprise_test.go Updated calendar schedule creation to use slog logger initialization
server/cron/calendar_cron.go Updated all calendar cron functions to accept *slog.Logger
server/cron/calendar_cron_test.go Updated test logger initialization to use slog patterns
server/platform/mysql/retry.go Added context.Context parameter to TriggerFatalError and SetFatalErrorHandler
server/platform/mysql/retry_test.go Updated tests to pass context to TriggerFatalError
server/platform/mysql/common.go Updated TriggerFatalError calls to pass context
server/datastore/mysql/sessions.go Updated TriggerFatalError call to pass context

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

@coderabbitai

coderabbitai Bot commented Feb 27, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

This pull request migrates logging infrastructure from the custom logging.Logger type to Go's standard library log/slog.Logger across multiple Fleet codebase packages. Changes include updating function signatures in cron scheduling, vulnerability processing, calendar cron, and service components to accept *slog.Logger instead of *logging.Logger. Additionally, the MySQL fatal error handling APIs are updated to propagate context through error callbacks in TriggerFatalError and SetFatalErrorHandler. No behavioral or control-flow changes are made to the underlying cron scheduling logic, vulnerability scanning, or database operations.

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.96% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive While most changes are slog migration-related, the TriggerFatalError context parameter additions appear tangential to the core slog migration objective and lack clear justification. Clarify whether context-threading through TriggerFatalError is necessary for the slog migration or if it should be a separate PR.
Description check ❓ Inconclusive The PR description is incomplete and vague. While it references the related issue (#40540/40054) and mentions slog migration work, it lacks detailed explanation of changes and rationale. Provide a comprehensive description of what changes were made, why they were made, and what impact they have. Include details about the slog migration scope and any breaking changes to public APIs.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'slog migration: initLogger + serve.go + cron + schedule' accurately summarizes the main changes, clearly identifying the slog migration work across the specified components.
Linked Issues check ✅ Passed The PR effectively addresses the slog migration objective from #40054 by replacing logging.Logger with slog.Logger across initLogger, serve.go, cron, schedule, and related components as required.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch victor/40054-slog-initlogger

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 (7)
server/service/integration_mdm_test.go (1)

332-369: Consider extracting repeated job lifecycle logging into a small helper.

The start/complete logging pattern is duplicated across several scheduled jobs, which makes future edits noisy.

Refactor sketch
+logJob := func(ctx context.Context, jobName string, onDone func(), run func(context.Context) error) error {
+  logger.InfoContext(ctx, "Starting job", "job", jobName, "test", s.T().Name(), "time", time.Now())
+  if onDone != nil {
+    defer func() {
+      logger.InfoContext(ctx, "Completing job", "job", jobName, "test", s.T().Name(), "time", time.Now())
+      onDone()
+    }()
+  }
+  return run(ctx)
+}

Then call it from each schedule.WithJob(...) closure.

Also applies to: 429-437

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

In `@server/service/integration_mdm_test.go` around lines 332 - 369, The repeated
start/complete logging and onProfileJobDone defer logic in each schedule.WithJob
closure (seen around the closures for "manage_apple_profiles",
"manage_apple_declarations", and "manage_windows_profiles" which call
logger.InfoContext and s.onProfileJobDone, then invoke
ReconcileAppleProfiles/ReconcileAppleDeclarations/ReconcileWindowsProfiles)
should be extracted into a small helper wrapper (e.g., wrapJob(jobName string,
job func(context.Context) error) func(context.Context) error) that logs
start/complete with time, handles the s.onProfileJobDone defer, calls the passed
job function, and returns its error; replace each inline closure passed to
schedule.WithJob with a call to this wrapper passing the specific reconcile
function.
cmd/fleet/cron.go (6)

187-187: Empty message string in log call.

Same issue as above—consider using a descriptive message.

Suggested fix
-	logger.DebugContext(ctx, "", "vulnAutomationEnabled", vulnAutomationEnabled)
+	logger.DebugContext(ctx, "vulnerability automation status", "automation_enabled", vulnAutomationEnabled)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleet/cron.go` at line 187, The log call uses an empty message string in
logger.DebugContext(ctx, "", "vulnAutomationEnabled", vulnAutomationEnabled);
update this call to supply a descriptive message (e.g., "vulnerability
automation enabled" or similar) while keeping the existing structured key
"vulnAutomationEnabled" and value vulnAutomationEnabled so the log entry is
meaningful; locate the logger.DebugContext invocation in cron.go and replace the
empty string argument with the descriptive message.

459-460: Empty message string in log call.

Suggested fix
-		logger.DebugContext(refreshCtx, "", "goval_dictionary-sync-downloaded", d)
+		logger.DebugContext(refreshCtx, "goval_dictionary sync downloaded", "file", d)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleet/cron.go` around lines 459 - 460, The log call inside the loop over
downloaded uses logger.DebugContext(refreshCtx, "",
"goval_dictionary-sync-downloaded", d) with an empty message string; update the
call to provide a meaningful message (e.g., "goval dictionary downloaded" or
similar) so the log entry isn't missing a human-readable message, keeping the
same context (refreshCtx), tag ("goval_dictionary-sync-downloaded") and payload
(d) to preserve structure and semantics.

306-306: Inconsistent slog key-value pattern.

The key "found new" contains a space which is atypical. Consider using snake_case or camelCase for keys.

Suggested fix
-	logger.DebugContext(ctx, "custom-vulnerabilities-analysis-done", "found new", len(vulns))
+	logger.DebugContext(ctx, "custom-vulnerabilities-analysis-done", "found_new", len(vulns))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleet/cron.go` at line 306, The log call using logger.DebugContext with
the kv pair key "found new" uses a space-including key which breaks the
project's slog key naming convention; update the call in the DebugContext
invocation (logger.DebugContext) to use a single-token key like "found_new" or
"foundNew" (and adjust any other callers if present) so the kv pair conforms to
snake_case/camelCase conventions and remains consistent with other structured
logs.

400-401: Empty message string in log call.

Suggested fix
-		logger.DebugContext(refreshCtx, "", "oval-sync-downloaded", d)
+		logger.DebugContext(refreshCtx, "oval sync downloaded", "file", d)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleet/cron.go` around lines 400 - 401, The log call uses an empty message
string in logger.DebugContext inside the loop over downloaded items; update that
call (in cmd/fleet/cron.go where logger.DebugContext is invoked for
"oval-sync-downloaded") to provide a meaningful message (e.g., "downloaded OVAL
file" or "downloaded OVAL feed entry") or a formatted message including d
details so the log is readable and informative.

356-361: Inconsistent slog key-value pattern with spaces.

Several keys contain spaces ("os name", "os version", "display version", "found new"). Consider using consistent key naming conventions (snake_case or camelCase) for better log parsing.

Suggested fix
 		logger.DebugContext(analyzeCtx, "msrc-analysis-done",
-			"os name", o.Name,
-			"os version", o.Version,
-			"display version", o.DisplayVersion,
+			"os_name", o.Name,
+			"os_version", o.Version,
+			"display_version", o.DisplayVersion,
 			"elapsed", elapsed,
-			"found new", len(r))
+			"found_new", len(r))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleet/cron.go` around lines 356 - 361, The log call using
logger.DebugContext(analyzeCtx, "msrc-analysis-done", ...) uses keys with spaces
("os name", "os version", "display version", "found new"); change these to a
consistent machine-friendly format (e.g., os_name, os_version, display_version,
found_new or camelCase osName, osVersion, displayVersion, foundNew) and update
the logger.DebugContext invocation accordingly (keeping analyzeCtx,
"msrc-analysis-done", o.Name, o.Version, o.DisplayVersion, elapsed, len(r) as
values tied to the new keys); also scan nearby/related logging calls to make key
naming consistent across the file.

91-91: Empty message string in log call.

The first argument after context should be a meaningful message. Here the message is empty and "periodicity" is used as a key-value attribute.

Suggested fix
-	logger.InfoContext(ctx, "", "periodicity", config.Periodicity)
+	logger.InfoContext(ctx, "vulnerability scan configuration", "periodicity", config.Periodicity)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleet/cron.go` at line 91, The log call uses an empty message string:
replace logger.InfoContext(ctx, "", "periodicity", config.Periodicity) with a
call that supplies a meaningful message (e.g., "cron periodicity configured" or
"starting cron") while keeping the key-value attribute "periodicity" and
config.Periodicity; update the invocation at the logger.InfoContext call site so
the first string argument is non-empty and descriptive.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@cmd/fleet/cron.go`:
- Line 187: The log call uses an empty message string in
logger.DebugContext(ctx, "", "vulnAutomationEnabled", vulnAutomationEnabled);
update this call to supply a descriptive message (e.g., "vulnerability
automation enabled" or similar) while keeping the existing structured key
"vulnAutomationEnabled" and value vulnAutomationEnabled so the log entry is
meaningful; locate the logger.DebugContext invocation in cron.go and replace the
empty string argument with the descriptive message.
- Around line 459-460: The log call inside the loop over downloaded uses
logger.DebugContext(refreshCtx, "", "goval_dictionary-sync-downloaded", d) with
an empty message string; update the call to provide a meaningful message (e.g.,
"goval dictionary downloaded" or similar) so the log entry isn't missing a
human-readable message, keeping the same context (refreshCtx), tag
("goval_dictionary-sync-downloaded") and payload (d) to preserve structure and
semantics.
- Line 306: The log call using logger.DebugContext with the kv pair key "found
new" uses a space-including key which breaks the project's slog key naming
convention; update the call in the DebugContext invocation (logger.DebugContext)
to use a single-token key like "found_new" or "foundNew" (and adjust any other
callers if present) so the kv pair conforms to snake_case/camelCase conventions
and remains consistent with other structured logs.
- Around line 400-401: The log call uses an empty message string in
logger.DebugContext inside the loop over downloaded items; update that call (in
cmd/fleet/cron.go where logger.DebugContext is invoked for
"oval-sync-downloaded") to provide a meaningful message (e.g., "downloaded OVAL
file" or "downloaded OVAL feed entry") or a formatted message including d
details so the log is readable and informative.
- Around line 356-361: The log call using logger.DebugContext(analyzeCtx,
"msrc-analysis-done", ...) uses keys with spaces ("os name", "os version",
"display version", "found new"); change these to a consistent machine-friendly
format (e.g., os_name, os_version, display_version, found_new or camelCase
osName, osVersion, displayVersion, foundNew) and update the logger.DebugContext
invocation accordingly (keeping analyzeCtx, "msrc-analysis-done", o.Name,
o.Version, o.DisplayVersion, elapsed, len(r) as values tied to the new keys);
also scan nearby/related logging calls to make key naming consistent across the
file.
- Line 91: The log call uses an empty message string: replace
logger.InfoContext(ctx, "", "periodicity", config.Periodicity) with a call that
supplies a meaningful message (e.g., "cron periodicity configured" or "starting
cron") while keeping the key-value attribute "periodicity" and
config.Periodicity; update the invocation at the logger.InfoContext call site so
the first string argument is non-empty and descriptive.

In `@server/service/integration_mdm_test.go`:
- Around line 332-369: The repeated start/complete logging and onProfileJobDone
defer logic in each schedule.WithJob closure (seen around the closures for
"manage_apple_profiles", "manage_apple_declarations", and
"manage_windows_profiles" which call logger.InfoContext and s.onProfileJobDone,
then invoke
ReconcileAppleProfiles/ReconcileAppleDeclarations/ReconcileWindowsProfiles)
should be extracted into a small helper wrapper (e.g., wrapJob(jobName string,
job func(context.Context) error) func(context.Context) error) that logs
start/complete with time, handles the s.onProfileJobDone defer, calls the passed
job function, and returns its error; replace each inline closure passed to
schedule.WithJob with a call to this wrapper passing the specific reconcile
function.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9165b31 and 2bd4dcd.

📒 Files selected for processing (15)
  • cmd/fleet/cron.go
  • cmd/fleet/cron_test.go
  • cmd/fleet/main.go
  • cmd/fleet/serve.go
  • cmd/fleet/serve_test.go
  • cmd/fleet/vuln_process.go
  • server/cron/calendar_cron.go
  • server/cron/calendar_cron_test.go
  • server/datastore/mysql/sessions.go
  • server/platform/mysql/common.go
  • server/platform/mysql/retry.go
  • server/platform/mysql/retry_test.go
  • server/service/integration_enterprise_test.go
  • server/service/integration_mdm_test.go
  • server/service/schedule/schedule.go
🔥 Files not summarized due to errors (2)
  • server/service/integration_mdm_test.go: Error: Server error: no LLM provider could handle the message
  • server/service/integration_enterprise_test.go: Error: Server error: no LLM provider could handle the message

@getvictor
getvictor marked this pull request as ready for review February 27, 2026 17:15
@getvictor
getvictor requested a review from a team as a code owner February 27, 2026 17:15
@getvictor
getvictor merged commit bf9180e into main Feb 27, 2026
60 checks passed
@getvictor
getvictor deleted the victor/40054-slog-initlogger branch February 27, 2026 20:29
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 (3)

4 participants