Skip to content

Replaced all kitlog.Logger instances with the intermediate *logging.Logger - #40425

Merged
getvictor merged 3 commits into
mainfrom
victor/40054-remove-kitlog
Feb 25, 2026
Merged

Replaced all kitlog.Logger instances with the intermediate *logging.Logger#40425
getvictor merged 3 commits into
mainfrom
victor/40054-remove-kitlog

Conversation

@getvictor

@getvictor getvictor commented Feb 24, 2026

Copy link
Copy Markdown
Member

Related issue: Resolves #40054

Checklist for submitter

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

Testing

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

Summary by CodeRabbit

  • Refactor
    • Consolidated and standardized internal logging infrastructure across the application by adopting a unified logging package throughout the codebase, replacing previous external logging dependencies.

@getvictor

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Feb 24, 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 is part of the ongoing slog migration effort (continuing from #38889, tracked in #40054). It replaces all kitlog.Logger (go-kit/log) instances with the intermediate *logging.Logger type throughout the codebase.

Changes:

  • Updated all function signatures accepting logger parameters from kitlog.Logger to *logging.Logger
  • Added AddSource field to logging.Options to enable source file and line number in log entries
  • Removed compile-time assertion that *Logger implements kitlog.Logger (intentional move away from kitlog)
  • Created zerologSlogHandler in orbit SCEP client to adapt zerolog.Logger to slog.Handler for use with *logging.Logger
  • Enhanced Logger.With() to return *Logger directly instead of kitlog.Logger, eliminating need for type assertions

Reviewed changes

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

Show a summary per file
File Description
server/platform/logging/logging.go Added AddSource field to Options struct for source file logging
server/platform/logging/kitlog_adapter.go Removed kitlog.Logger compile-time assertion, removed import of kitlog package
server/platform/logging/kitlog_adapter_test.go Removed TestKitlogAdapterLevels test (level wrappers being phased out), simplified test setup
server/service/*.go Updated logger parameter types from kitlog.Logger to *logging.Logger across service layer
server/datastore/mysql/*.go Updated logger parameter types in datastore functions
server/logging/*.go Updated all log writer constructors to accept *logging.Logger
server/mdm/scep/**/*.go Updated SCEP server/client logger types and removed unnecessary level wrappers
ee/server/service/*.go Updated EE service layer logger types
ee/orbit/pkg/scep/scep.go Implemented zerologSlogHandler to bridge zerolog and slog/logging.Logger
cmd/fleet/serve.go Updated devSQLInterceptor and helper function logger types
cmd/fleetctl/**/*.go Updated fleetctl command logger types
pkg/mdm/mdmtest/apple.go Updated test MDM client logger type

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

Comment thread ee/orbit/pkg/scep/scep.go
@coderabbitai

coderabbitai Bot commented Feb 24, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

This PR systematically migrates logging infrastructure across the codebase from go-kit/log types to a platform-specific *logging.Logger type. The changes replace log.Logger and kitlog.Logger references with *logging.Logger from the server/platform/logging package, update function and method signatures accordingly, and adjust logger initialization and usage patterns. Affected areas include command-line tools, SCEP services, MDM operations, logging backend implementations, datastore functions, and service endpoints throughout the repository.

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.80% 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 does not follow the required template structure. Complete the PR description by filling in all applicable sections from the template: clarify what changes were made, confirm input validation and SQL injection prevention, detail testing performed, address database migration considerations if applicable, and verify fleetd/orbit/Fleet Desktop compatibility where relevant.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and accurately summarizes the main change: replacing all kitlog.Logger instances with *logging.Logger, which aligns with the changeset content.
Linked Issues check ✅ Passed The PR addresses issue #40054 (slog migration continuation), which aligns with the changeset's focus on replacing kitlog.Logger with *logging.Logger as part of ongoing slog migration work [#40054].
Out of Scope Changes check ✅ Passed All changes are within scope: logger type replacements from kitlog.Logger to *logging.Logger across multiple files, plus one new field addition (AddSource) to logging Options. No unrelated modifications detected.

✏️ 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-remove-kitlog

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.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
server/platform/logging/kitlog_adapter_test.go (1)

14-37: ⚠️ Potential issue | 🟠 Major

Avoid parallel subtests sharing a single handler.
TestKitlogAdapter runs subtests in parallel while sharing one handler/adapter, so LastRecord() can observe logs from the other subtest and make this flaky. Create a handler/adapter per subtest or drop t.Parallel() inside the subtests.

✅ Suggested fix: give each subtest its own handler/adapter
 func TestKitlogAdapter(t *testing.T) {
 	t.Parallel()
-	handler := testutils.NewTestHandler()
-	adapter := NewLogger(slog.New(handler))
-
 	t.Run("basic logging via Log method", func(t *testing.T) {
 		t.Parallel()
+		handler := testutils.NewTestHandler()
+		adapter := NewLogger(slog.New(handler))
 
 		err := adapter.Log("msg", "hello world", "key", "value")
 		require.NoError(t, err)
@@
 	t.Run("with context via With", func(t *testing.T) {
 		t.Parallel()
+		handler := testutils.NewTestHandler()
+		adapter := NewLogger(slog.New(handler))
 
 		contextLogger := adapter.With("component", "test-component")
 		err := contextLogger.Log("msg", "message with context")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/platform/logging/kitlog_adapter_test.go` around lines 14 - 37, The
test shares a single handler/adapter across parallel subtests which makes
LastRecord() flaky; for each subtest create its own handler and adapter instead
of using the outer handler/adapter (e.g., call testutils.NewTestHandler() and
NewLogger(slog.New(handler)) inside each t.Run) so contextLogger :=
adapter.With(...) and calls to adapter.Log or contextLogger.Log operate on an
isolated handler per subtest; update both subtests in TestKitlogAdapter to
initialize their own handler/adapter and leave the t.Parallel() calls if you
want parallelism.
🧹 Nitpick comments (4)
ee/orbit/pkg/scep/scep.go (1)

311-313: WithGroup silently drops the group name.

Returning h unchanged means any grouped attributes from callers will lose their namespace. This is acceptable if slog groups are never used on this path, but worth a brief comment so future maintainers don't expect group support.

Optional: add a comment
 func (h *zerologSlogHandler) WithGroup(_ string) slog.Handler {
-	return h
+	// zerolog does not support slog groups; attributes within a group
+	// are flattened into the parent namespace.
+	return h
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ee/orbit/pkg/scep/scep.go` around lines 311 - 313, The WithGroup method on
zerologSlogHandler currently ignores the provided group name and returns h
unchanged, which silently drops grouped attribute namespaces; update the
WithGroup implementation to either preserve group semantics or, if groups are
intentionally unsupported, add a concise comment above
zerologSlogHandler.WithGroup stating that slog groups are intentionally ignored
on this handler (mentioning any rationale such as compatibility with zerolog or
no-op behavior) so future maintainers won't expect group support; keep the
function body unchanged if choosing the comment route.
server/mdm/scep/cmd/scepclient/scepclient.go (1)

64-64: lginfo is now a redundant alias for logger.

Since the previous level-filtered wrapper (likely level.Info(logger)) is gone, lginfo and logger point to the same instance. The variable can be removed and its two use-sites (lines 187, 191) can call logger.Log(...) directly.

♻️ Proposed cleanup
-	lginfo := logger
-
 	client, err := scepclient.New(cfg.serverURL, logger)
-		lginfo.Log("pkiStatus", "PENDING", "msg", "sleeping for 30 seconds, then trying again.")
+		logger.Log("pkiStatus", "PENDING", "msg", "sleeping for 30 seconds, then trying again.")
-	lginfo.Log("pkiStatus", "SUCCESS", "msg", "server returned a certificate.")
+	logger.Log("pkiStatus", "SUCCESS", "msg", "server returned a certificate.")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/mdm/scep/cmd/scepclient/scepclient.go` at line 64, Remove the
redundant lginfo alias and call logger directly: delete the lginfo := logger
declaration and replace the two lginfo.Log(...) call sites (currently using
lginfo at the scepclient command execution points) with logger.Log(...)
(preserving the same log level and fields/arguments). Ensure no other references
to lginfo remain and run go vet/static checks to confirm compilation.
server/service/mdm_scep.go (1)

26-26: Wire the provided logger or remove the parameter.
NewSCEPService accepts a logger but always sets debugLogger to a no-op, so caller-supplied logging is ignored. Consider using the passed logger (with a nil fallback) or dropping the parameter to avoid a misleading API.

Suggested fix
 func NewSCEPService(ds fleet.MDMAssetRetriever, signer scepserver.CSRSignerContext, logger *logging.Logger) scepserver.Service {
+	if logger == nil {
+		logger = logging.NewNopLogger()
+	}
 	return &service{
 		signer:      signer,
-		debugLogger: logging.NewNopLogger(),
+		debugLogger: logger,
 		ds:          ds,
 	}
 }

Also applies to: 86-90

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

In `@server/service/mdm_scep.go` at line 26, NewSCEPService currently ignores the
provided logger and always assigns a no-op to the service field debugLogger;
update NewSCEPService (and the other constructor/initialization at the block
around lines 86-90) to wire the caller-supplied logger into the service by
assigning s.debugLogger = logger when logger != nil and only fall back to a
no-op when logger is nil (alternatively remove the logger parameter if you
prefer to not accept it); reference the NewSCEPService function and the service
struct's debugLogger field when making the change.
server/service/endpoint_setup.go (1)

329-344: Pre-existing: defer in loop leaks file descriptors until function return.

Not introduced by this PR, but worth noting: defer resp.Body.Close() (line 333) and defer file.Close() (line 344) are inside the for loop but deferred to function exit. For many scripts, this accumulates open file handles. Consider closing them explicitly at the end of each iteration or extracting the loop body into a helper function.

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

In `@server/service/endpoint_setup.go` around lines 329 - 344, The loop that
downloads scripts calls httpClient.Do(req) and then uses defer resp.Body.Close()
and defer file.Close() inside the loop body, which defers closes until the
surrounding function returns and can leak file descriptors; modify the code so
resp.Body.Close() and file.Close() are called explicitly at the end of each
iteration (or move the loop body into a helper like downloadScript(scriptName,
localPath) so the defers run at helper return) — ensure you remove the in-loop
defers and replace them with immediate Close() calls (or keep defers inside the
new helper) for the http response and the created file obtained via
os.Create(localPath).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@ee/orbit/pkg/scep/scep.go`:
- Around line 307-309: WithAttrs currently returns &zerologSlogHandler{logger:
h.logger, attrs: append(h.attrs, attrs...)}, which can reuse h.attrs' backing
array and cause sibling handlers to share/overwrite entries; change WithAttrs
(method on zerologSlogHandler) to allocate a fresh slice (or use slices.Concat)
and copy both h.attrs and the incoming attrs into it before returning the new
zerologSlogHandler so the parent’s backing array is never aliased.
- Around line 290-305: The Handle method currently ignores r.Level and always
starts with h.logger.Info(), losing severity; update zerologSlogHandler.Handle
to inspect r.Level and choose the appropriate zerolog event (e.g.,
h.logger.Debug(), Info(), Warn(), Error(), Trace() or Fatal() as appropriate)
before attaching attrs and message, using r.Level to map
slog.LevelDebug/Info/Warn/Error etc. to the corresponding zerolog level and then
proceed to call event.Interface(...) for h.attrs and r.Attrs(...) and finally
event.Msg(r.Message).

---

Outside diff comments:
In `@server/platform/logging/kitlog_adapter_test.go`:
- Around line 14-37: The test shares a single handler/adapter across parallel
subtests which makes LastRecord() flaky; for each subtest create its own handler
and adapter instead of using the outer handler/adapter (e.g., call
testutils.NewTestHandler() and NewLogger(slog.New(handler)) inside each t.Run)
so contextLogger := adapter.With(...) and calls to adapter.Log or
contextLogger.Log operate on an isolated handler per subtest; update both
subtests in TestKitlogAdapter to initialize their own handler/adapter and leave
the t.Parallel() calls if you want parallelism.

---

Nitpick comments:
In `@ee/orbit/pkg/scep/scep.go`:
- Around line 311-313: The WithGroup method on zerologSlogHandler currently
ignores the provided group name and returns h unchanged, which silently drops
grouped attribute namespaces; update the WithGroup implementation to either
preserve group semantics or, if groups are intentionally unsupported, add a
concise comment above zerologSlogHandler.WithGroup stating that slog groups are
intentionally ignored on this handler (mentioning any rationale such as
compatibility with zerolog or no-op behavior) so future maintainers won't expect
group support; keep the function body unchanged if choosing the comment route.

In `@server/mdm/scep/cmd/scepclient/scepclient.go`:
- Line 64: Remove the redundant lginfo alias and call logger directly: delete
the lginfo := logger declaration and replace the two lginfo.Log(...) call sites
(currently using lginfo at the scepclient command execution points) with
logger.Log(...) (preserving the same log level and fields/arguments). Ensure no
other references to lginfo remain and run go vet/static checks to confirm
compilation.

In `@server/service/endpoint_setup.go`:
- Around line 329-344: The loop that downloads scripts calls httpClient.Do(req)
and then uses defer resp.Body.Close() and defer file.Close() inside the loop
body, which defers closes until the surrounding function returns and can leak
file descriptors; modify the code so resp.Body.Close() and file.Close() are
called explicitly at the end of each iteration (or move the loop body into a
helper like downloadScript(scriptName, localPath) so the defers run at helper
return) — ensure you remove the in-loop defers and replace them with immediate
Close() calls (or keep defers inside the new helper) for the http response and
the created file obtained via os.Create(localPath).

In `@server/service/mdm_scep.go`:
- Line 26: NewSCEPService currently ignores the provided logger and always
assigns a no-op to the service field debugLogger; update NewSCEPService (and the
other constructor/initialization at the block around lines 86-90) to wire the
caller-supplied logger into the service by assigning s.debugLogger = logger when
logger != nil and only fall back to a no-op when logger is nil (alternatively
remove the logger parameter if you prefer to not accept it); reference the
NewSCEPService function and the service struct's debugLogger field when making
the change.

ℹ️ 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 13a8d9d and d8e26cf.

📒 Files selected for processing (71)
  • cmd/fleet/serve.go
  • cmd/fleetctl/fleetctl/preview.go
  • cmd/fleetctl/integrationtest/gitops/gitops_enterprise_integration_test.go
  • cmd/osquery-perf/hostidentity/hostidentity.go
  • ee/orbit/pkg/scep/scep.go
  • ee/orbit/pkg/scep/scep_test.go
  • ee/server/service/condaccess/depot/depot.go
  • ee/server/service/condaccess/idp.go
  • ee/server/service/condaccess/scep.go
  • ee/server/service/est/est.go
  • ee/server/service/hostidentity/httpsig/httpsig.go
  • ee/server/service/hostidentity/httpsig/middleware.go
  • ee/server/service/hostidentity/scep.go
  • ee/server/service/scep_proxy.go
  • ee/server/service/scep_proxy_test.go
  • ee/server/service/software_installers.go
  • ee/server/service/testing_utils.go
  • pkg/mdm/mdmtest/apple.go
  • server/datastore/mysql/apple_mdm.go
  • server/datastore/mysql/hosts.go
  • server/datastore/mysql/mdm.go
  • server/datastore/mysql/mysql.go
  • server/datastore/mysql/operating_system_vulnerabilities.go
  • server/datastore/mysql/scim.go
  • server/datastore/mysql/software.go
  • server/logging/filesystem.go
  • server/logging/filesystem_test.go
  • server/logging/firehose.go
  • server/logging/firehose_test.go
  • server/logging/kinesis.go
  • server/logging/kinesis_test.go
  • server/logging/lambda.go
  • server/logging/lambda_test.go
  • server/logging/logging.go
  • server/logging/nats.go
  • server/logging/nats_test.go
  • server/logging/pubsub.go
  • server/logging/webhook.go
  • server/logging/webhook_test.go
  • server/mdm/lifecycle/lifecycle.go
  • server/mdm/lifecycle/lifecycle_test.go
  • server/mdm/scep/client/client.go
  • server/mdm/scep/cmd/scepclient/scepclient.go
  • server/mdm/scep/cmd/scepserver/scepserver.go
  • server/mdm/scep/csrverifier/executable/csrverifier.go
  • server/mdm/scep/server/endpoint.go
  • server/mdm/scep/server/service.go
  • server/mdm/scep/server/service_logging.go
  • server/mdm/scep/server/transport.go
  • server/mdm/scep/server/transport_test.go
  • server/platform/logging/kitlog_adapter.go
  • server/platform/logging/kitlog_adapter_test.go
  • server/platform/logging/logging.go
  • server/service/activities.go
  • server/service/async/async.go
  • server/service/devices_url_auth_test.go
  • server/service/endpoint_campaigns.go
  • server/service/endpoint_middleware.go
  • server/service/endpoint_middleware_test.go
  • server/service/endpoint_setup.go
  • server/service/endpoint_setup_test.go
  • server/service/endpoint_utils.go
  • server/service/frontend.go
  • server/service/frontend_test.go
  • server/service/integrationtest/scep_server/scep.go
  • server/service/mdm_scep.go
  • server/service/modules/activities/activities.go
  • server/service/osquery.go
  • server/service/service_campaign_test.go
  • server/service/service_campaigns.go
  • server/service/software_installers_test.go
💤 Files with no reviewable changes (1)
  • server/platform/logging/kitlog_adapter.go

Comment thread ee/orbit/pkg/scep/scep.go
Comment thread ee/orbit/pkg/scep/scep.go
@getvictor
getvictor marked this pull request as ready for review February 24, 2026 20:37
@getvictor
getvictor requested a review from a team as a code owner February 24, 2026 20:37
@codecov

codecov Bot commented Feb 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 58.69565% with 38 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.29%. Comparing base (a3af9bd) to head (9810ee2).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
ee/orbit/pkg/scep/scep.go 65.51% 9 Missing and 1 partial ⚠️
server/mdm/scep/cmd/scepclient/scepclient.go 0.00% 6 Missing ⚠️
server/mdm/scep/cmd/scepserver/scepserver.go 0.00% 6 Missing ⚠️
cmd/fleet/serve.go 0.00% 1 Missing ⚠️
cmd/fleetctl/fleetctl/preview.go 50.00% 1 Missing ⚠️
cmd/osquery-perf/hostidentity/hostidentity.go 0.00% 1 Missing ⚠️
pkg/mdm/mdmtest/apple.go 66.66% 1 Missing ⚠️
server/logging/filesystem.go 50.00% 1 Missing ⚠️
server/logging/firehose.go 0.00% 1 Missing ⚠️
server/logging/kinesis.go 0.00% 1 Missing ⚠️
... and 9 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #40425      +/-   ##
==========================================
+ Coverage   66.26%   66.29%   +0.02%     
==========================================
  Files        2460     2460              
  Lines      196773   197278     +505     
  Branches     8754     8596     -158     
==========================================
+ Hits       130394   130782     +388     
- Misses      54563    54656      +93     
- Partials    11816    11840      +24     
Flag Coverage Δ
backend 68.14% <58.69%> (+<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.

…itlog

# Conflicts:
#	ee/server/service/condaccess/depot/depot.go
#	server/datastore/mysql/apple_mdm.go
#	server/datastore/mysql/hosts.go
#	server/datastore/mysql/mdm.go
#	server/datastore/mysql/mysql.go
#	server/datastore/mysql/operating_system_vulnerabilities.go
#	server/datastore/mysql/scim.go
#	server/datastore/mysql/software.go

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

I see we switched to using *logging.Logger everywhere. Is the goal to eventually use .SlogLogger() everywhere?

Comment thread ee/orbit/pkg/scep/scep.go
delete(fields, "msg")
}
}
func (h *zerologSlogHandler) Handle(_ context.Context, r slog.Record) error {

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.

The old Log method didn't use the context, this one accepts it. Do we want to use it anywhere? Maybe for the request or trace id? idk just a thought. Non-block comment.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, we want to use context if we can, since then we can link log lines to OTEL traces.
I'm just focusing on transitioning to slog and not fixing context everywhere. (I fix it some places if not too hard.)

@getvictor
getvictor merged commit c14bea4 into main Feb 25, 2026
50 checks passed
@getvictor
getvictor deleted the victor/40054-remove-kitlog branch February 25, 2026 00:52
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)

3 participants