Skip to content

refactor(log): unify Go logging to zap with rotation, strip per-package levels - #16261

Merged
yuzhichang merged 4 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port
Jun 23, 2026
Merged

yuzhichang merged 4 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port

Conversation

@yuzhichang

@yuzhichang yuzhichang commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

Refactor the Go agent port's logging so every log line — gin access, agent canvas events, harness warnings, fatal boot errors — flows through a single common.Logger (zap) backed by a rotated file, with structured fields, level filtering, and configurable rotation.

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 23, 2026
@coderabbitai

coderabbitai Bot commented Jun 23, 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 33f8dc6b-3a91-433b-90a8-41e7d9f9b7e6

📥 Commits

Reviewing files that changed from the base of the PR and between 9c23a31 and 941c086.

📒 Files selected for processing (3)
  • internal/agent/component/llm_credentials.go
  • internal/agent/component/universe_a_wrappers.go
  • internal/common/logger.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/agent/component/llm_credentials.go
  • internal/agent/component/universe_a_wrappers.go
  • internal/common/logger.go

📝 Walkthrough

Walkthrough

Replaces all standard-library log usage with structured zap-based internal/common logging across agent, canvas, harness, DAO, and service files. Introduces FileOutput with lumberjack log rotation, expands LogConfig, switches Gin request logging to common.GinLogger(), and removes per-package log-level tracking.

Changes

Structured Logging Overhaul

Layer / File(s) Summary
Logger core: FileOutput, Init, GinLogger, Error, ResolveCompress
internal/common/logger.go
Rewrites logger initialization with FileOutput struct and lumberjack rotation; replaces Init(level, logFile string) with Init(level string, file FileOutput); adds ResolveCompress; removes GetLogLevels/SetPackageLogLevel; updates Error to accept variadic zap fields; adds GinLogger() middleware with status-code-based level selection and has_query/query_len fields.
LogConfig expansion, lumberjack dependency, template docs
internal/server/config.go, go.mod, docker/service_conf.yaml.template
Adds Path, MaxSize, MaxBackups, MaxAge, Compress *bool to LogConfig; adds gopkg.in/natefinch/lumberjack.v2 v2.2.1 dependency; documents all rotation options in a commented YAML template block.
Service entrypoints: FileOutput wiring and GinLogger middleware
cmd/admin_server.go, cmd/ingestor.go, cmd/ragflow_cli.go, cmd/server_main.go
Updates all startup files to pass common.FileOutput structs (instead of plain filename strings) to common.Init; builds rotation-configured FileOutput from cfg.Log/config.Log after config load; removes conditional gin.Logger() debug middleware and replaces with common.GinLogger() + common.Recovery().
Router GinLogger wiring and log-level HTTP API simplification
internal/router/router.go, internal/handler/system.go
Switches router middleware from gin.Logger() to common.GinLogger(); GetLogLevel now returns a single global level via common.GetLevel(); SetLogLevel calls common.SetLevel and syncs config; pkg_name becomes optional; success response shape changes to { "level": req.Level }.
Agent canvas and component: log.Printf → common.* structured logging
internal/agent/canvas/compile.go, internal/agent/canvas/compile_test.go, internal/agent/canvas/runner.go, internal/agent/canvas/scheduler.go, internal/agent/canvas/stream.go, internal/agent/component/agent.go, internal/agent/component/llm.go, internal/agent/component/llm_credentials.go, internal/agent/component/message.go, internal/agent/component/universe_a_wrappers.go
Migrates all log.Printf calls to structured common.Debug/common.Info/common.Warn/common.Error with zap fields; updates compile tests to assert against a buffer-backed common.Logger override.
Sandbox, tools, harness, DAO, service: log.Printf → common.* structured logging
internal/agent/sandbox/self_managed.go, internal/agent/tool/code_exec.go, internal/harness/core/interrupt.go, internal/harness/graph/checkpoint/nats.go, internal/harness/graph/pregel/engine.go, internal/dao/database.go, internal/service/agent.go, internal/tokenizer/tokenizer_concurrent_test.go
Migrates remaining log.Printf/log.Fatal calls to structured common.* with zap fields across sandbox, tool, harness, DAO, and service layers; updates all import blocks to drop log and add common/zap.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#16035: Directly touches internal/agent/canvas/compile.go and compile_test.go legacy-Canvas logging behavior that this PR migrates from log.Printf to common.Info with zap fields.

Suggested labels

☯️ refactor, size:XXL

Poem

🐇 Hop hop, no more log.Printf today,
Structured fields now light the way!
Lumberjack spins the logs so neat,
GinLogger makes each request complete.
With zap and fields the bunny sings—
Clean logs for all the things! 🪵✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 67.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main refactoring: unifying Go logging to use zap with rotation while removing per-package log levels.
Description check ✅ Passed The PR description provides a comprehensive overview of what the refactoring solves and its objectives, meeting the template requirements despite being a single-paragraph explanation.
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.

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


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.

@yuzhichang yuzhichang added the ci Continue Integration label Jun 23, 2026
@yuzhichang yuzhichang changed the title fix(log): address CodeRabbit review on zap unification refactor(log): unify Go logging to zap with rotation, strip per-package levels Jun 23, 2026

@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: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/admin_server.go`:
- Around line 171-172: The admin server is registering common.GinLogger() before
calling r.Setup(ginEngine) in admin_server.go, which creates an inconsistency
with the pattern used in server_main.go. Move the common.GinLogger()
registration from admin_server.go line 171 (where
ginEngine.Use(common.GinLogger()) is called) into the admin router's Setup
method in admin/router.go so that the logger middleware is registered inside
Setup along with the route registrations, matching the established pattern used
in the main server's internal/router/router.go. This ensures consistent
middleware handling across all router implementations.

In `@internal/agent/component/llm_credentials.go`:
- Around line 68-70: The common.Debug calls logging LLM credentials in the
llm_credentials.go file are emitting the full base_url value, which may contain
embedded secrets and poses a security risk. Locate both occurrences of the
zap.String("base_url", baseURL) field in the debug logs (around line 70 and
lines 126-130) and replace it with a sanitized alternative that either logs only
the presence or length of the base_url, or extracts and logs only the sanitized
host portion without any credentials or paths that could contain secrets.

In `@internal/agent/component/universe_a_wrappers.go`:
- Around line 440-443: The CodeExec wrapper invoke debug log at the common.Debug
call is exposing raw payloads via zap.Any() fields for params, inputs, and
merged parameters, which could leak sensitive secrets and execution details.
Replace these zap.Any() calls with safe metadata alternatives that only log
bounded information such as the count of items, presence indicators, or type
information instead of the actual payload content. Apply the same fix to the
similar debug logging around lines 488-492 that also uses zap.Any() for payload
fields.

In `@internal/common/logger.go`:
- Around line 294-310: The code creates duplicate "error" fields in 5xx log
entries by appending zap.String("error", last.Error()) to fields at line 297,
and then passing ginErr to the Error() function call at line 310, which
internally appends another zap.Error(ginErr) field. To fix this following Option
1, move the zap.String("error", last.Error()) append to only apply for non-5xx
responses (like the existing 4xx and 2xx/3xx paths with Warn and Info calls), so
that 5xx responses only use the structured error field from the Error()
function's error parameter rather than the string field, eliminating the
duplicate "error" field in the output.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0e51f7c7-bcf1-490a-9dd5-42ec38ed5f96

📥 Commits

Reviewing files that changed from the base of the PR and between 11e14a8 and 57767d0.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (28)
  • cmd/admin_server.go
  • cmd/ingestor.go
  • cmd/ragflow_cli.go
  • cmd/server_main.go
  • docker/service_conf.yaml.template
  • go.mod
  • internal/agent/canvas/compile.go
  • internal/agent/canvas/compile_test.go
  • internal/agent/canvas/runner.go
  • internal/agent/canvas/scheduler.go
  • internal/agent/canvas/stream.go
  • internal/agent/component/agent.go
  • internal/agent/component/llm.go
  • internal/agent/component/llm_credentials.go
  • internal/agent/component/message.go
  • internal/agent/component/universe_a_wrappers.go
  • internal/agent/sandbox/self_managed.go
  • internal/agent/tool/code_exec.go
  • internal/common/logger.go
  • internal/dao/database.go
  • internal/handler/system.go
  • internal/harness/core/interrupt.go
  • internal/harness/graph/checkpoint/nats.go
  • internal/harness/graph/pregel/engine.go
  • internal/router/router.go
  • internal/server/config.go
  • internal/service/agent.go
  • internal/tokenizer/tokenizer_concurrent_test.go

Comment thread cmd/admin_server.go Resolved
Comment thread internal/common/logger.go Resolved
yuzhichang and others added 3 commits June 23, 2026 15:35
Address CodeRabbit review comments on PR infiniflow#16260.

Security / privacy fixes:
- internal/common/logger.go (GinLogger): drop the raw query string
  from the logged path. Query params frequently carry OAuth codes,
  SAML responses, signed state, and API keys in callback URLs; there
  is no generic redaction strategy. Replace with has_query (bool) and
  query_len (int) fields so operators can still see that a query
  string was present and how long it was, without ever seeing its
  contents.
- internal/agent/component/llm_credentials.go: replace
  zap.String("api_key", apiKey) with zap.Bool("api_key_present",
  apiKey != "") in both the tenant_llm OK and new-table OK debug
  log sites. API keys must never appear in log files.
- internal/agent/tool/code_exec.go: bound the script/arguments and
  stdout/stderr fields to lengths and presence flags. Scripts and
  shell output routinely contain credentials passed as environment
  variables or printed by the script itself; logging the full bodies
  exposes them to anyone with read access to logs/server_main.log.

Bug / perf fix:
- cmd/server_main.go: remove the duplicate common.GinLogger()
  registration. router.Setup already registers it (router.go:126);
  registering it again at server_main.go:330 caused every request to
  emit two access-log lines. Replaced with a comment explaining why
  the registration lives in Setup.

Doc fix:
- internal/handler/system.go: correct the SetLogLevel doc comment to
  reflect the actual binding — only the level field is enforced;
  pkg_name is accepted but ignored, so saying "pkg_name and level
  are required" was misleading. The "pkg_name and level are
  required" error message string is preserved verbatim so existing
  clients that match on it keep working; only the comment is fixed.

Verified:
  bash build.sh --go    (all 4 binaries built)
  bash build.sh --test   (all packages pass; zero failures)

Co-Authored-By: Claude <[email protected]>
Address the 3 remaining unresolved CodeRabbit review comments on PR infiniflow#16261.

Security / privacy fixes:
- internal/agent/component/llm_credentials.go: replace
  zap.String("base_url", baseURL) with zap.Bool("base_url_present",
  baseURL != "") in both the tenant_llm OK and new-table OK debug
  log sites. base_url can carry embedded credentials when the model
  provider's endpoint embeds them in the URL (e.g.
  https://user:password@host/v1), and the same kind of credential
  leak we already guarded against for api_key applies here.

- internal/agent/component/universe_a_wrappers.go: bound the CodeExec
  wrapper debug payloads to counts and presence flags. The wrapper
  Invoke() log at line 440 was dumping raw params / inputs / merged
  maps; applyCodeExecBusinessOutputs at line 488 was dumping decoded,
  resolved_raw_result, content, and outputs. Scripts and their
  arguments routinely carry env vars, secrets, and DB connection
  strings; structured debug logs should never serialize them.

Bug fix:
- internal/common/logger.go (GinLogger): the 5xx branch logged the
  same error twice — once as zap.String("error", last.Error())
  appended to fields, and once as the structured zap.Error field
  emitted by common.Error() from its err arg. Two "error" fields
  in one record confuse downstream aggregation (Splunk / Loki /
  Elasticsearch dedupe keys can collapse the wrong one). Skip the
  string form when status >= 500; the structured zap.Error stays.
  4xx / 2xx-3xx paths still emit the string field because Warn /
  Info do not accept an err arg.

Verified:
  bash build.sh --go    (all 4 binaries built)
  bash build.sh --test   (all packages pass; zero failures)

Co-Authored-By: Claude <[email protected]>
@codecov

codecov Bot commented Jun 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (11e14a8) to head (941c086).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16261   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

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

@yuzhichang
yuzhichang merged commit 2362210 into infiniflow:main Jun 23, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant