Skip to content

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

Closed
yuzhichang wants to merge 2 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port
Closed

yuzhichang wants to merge 2 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

📝 Walkthrough

Walkthrough

The PR migrates all Go logging from the standard log package to a structured zap-backed logger in internal/common. Init now accepts a FileOutput struct enabling lumberjack file rotation. Per-package log-level APIs are removed in favor of a single global level. A GinLogger middleware is introduced. LogConfig gains rotation fields. All call sites across cmd, agent, harness, service, dao, and router packages are updated accordingly.

Changes

Structured Logging Infrastructure and Migration

Layer / File(s) Summary
Logger core: FileOutput, Init, GinLogger, ResolveCompress
internal/common/logger.go, go.mod
Init signature changes to accept FileOutput (path + rotation settings); builds a zapcore tee writing to stdout and an optional lumberjack-backed rotating file. Per-package level state (pkgLevels, levelMu, GetLogLevels, SetPackageLogLevel) is removed. Error gains variadic zap.Field args and skips the zap.Error field when err is nil. ResolveCompress(*bool) bool and GinLogger() gin.HandlerFunc are added. lumberjack.v2 is added as a direct dependency.
LogConfig schema and template documentation
internal/server/config.go, docker/service_conf.yaml.template
LogConfig gains Path, MaxSize, MaxBackups, MaxAge, and Compress *bool fields with inline docs. A commented-out log: block is added to the service config template.
Log level handler simplified to global-only
internal/handler/system.go
GetLogLevel returns {"level": <global>} instead of per-package map. SetLogLevel calls common.SetLevel globally; PkgName loses binding:"required"; success response drops pkg_name.
Server startup and router middleware wiring
cmd/admin_server.go, cmd/server_main.go, cmd/ingestor.go, cmd/ragflow_cli.go, internal/router/router.go
All entry points pass common.FileOutput to Init and rebuild it from config.Log after load. Conditional gin.Logger() replaced with unconditional common.GinLogger() in cmd binaries and internal/router.
Agent canvas structured logging migration
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
log.Printf calls replaced with common.Info/Debug/Warn/Error plus zap fields across compile, runner panic recovery, interrupt handling, scheduler node-start, and SSE stream drop paths. Tests updated to capture logs via common.Logger buffer swap.
Agent component/tool/sandbox structured logging migration
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
All log.Printf debug/warn/error calls replaced with common.Debug/Warn/Error using structured zap fields across LLM invocation, credential resolution, message memory-save, code exec wrappers, sandbox execution, and tool invocation paths.
Harness, service, dao, and test structured logging migration
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
log.Printf/log.Fatal replaced with common.Warn/Info/Error/Fatal/Debug plus zap fields in HMAC key warning, NATS GC purge, async checkpoint error, DB provider loading, and agent run tracking. Tokenizer test Init updated to FileOutput{}.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#16035: Touches the same internal/agent/canvas/compile.go legacy-node warning and its test in compile_test.go, directly overlapping with this PR's log migration for those files.

Suggested reviewers

  • JinHai-CN
  • Haruko386

Poem

🐇 Hop hop, the logs are neat,
No more log.Printf to beat!
With zap fields flying through the air,
And lumberjack rotating with care —
Structured JSON, a tidy treat,
This rabbit's logging is complete! 🪵✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 67.65% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description provides a clear statement of what the PR does (refactor logging to centralize through common.Logger with zap, rotation, and structured fields) but lacks structured sections as specified in the template. Add a structured description following the template by including a 'What problem does this PR solve?' section with background context and a 'Type of change' checklist to clearly document the refactoring category.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: unifying Go logging to zap with rotation and removing per-package levels, which aligns with the changeset's core objective.
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
@dosubot dosubot Bot added the ☯️ refactor Pull request that refactor/refine code label Jun 23, 2026
@yuzhichang
yuzhichang marked this pull request as draft June 23, 2026 06:30
@yuzhichang
yuzhichang marked this pull request as ready for review June 23, 2026 06:30

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

🧹 Nitpick comments (6)
internal/agent/canvas/compile.go (1)

120-120: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Use Warn for the decoder-bypass guard log.

This path is explicitly documented as a warning/regression signal; logging it at Info makes it disappear under warn-level production configs.

Suggested change
-			common.Info("canvas: Compile received Canvas with legacy LoopItem/IterationItem/Iteration nodes; this path bypassed dsl.NormalizeForCanvas — the fold step is not applied", zap.Int("n", n))
+			common.Warn("canvas: Compile received Canvas with legacy LoopItem/IterationItem/Iteration nodes; this path bypassed dsl.NormalizeForCanvas — the fold step is not applied", zap.Int("n", n))
🤖 Prompt for 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.

In `@internal/agent/canvas/compile.go` at line 120, The decoder-bypass guard log
message in the canvas compile function should be logged at the Warn level
instead of Info level to ensure it appears in production configurations with
warn-level logging. Replace the common.Info call with common.Warn in the
statement that logs the message about legacy LoopItem/IterationItem/Iteration
nodes being received, keeping all the existing parameters and message content
unchanged.
internal/common/logger.go (3)

46-49: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Doc references the wrong helper name.

The comment says "see resolveCompress", but the exported helper is ResolveCompress (Line 249). Minor, but worth correcting for grep-ability.

🤖 Prompt for 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.

In `@internal/common/logger.go` around lines 46 - 49, The comment in the LogConfig
documentation block references a helper function as "resolveCompress" but the
actual exported function name is "ResolveCompress" with a capital R. Update the
comment to use the correct function name "ResolveCompress" so that it matches
the actual implementation and improves grep-ability for developers looking for
references to this helper.

288-304: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Duplicate error field on 5xx responses that carry c.Errors.

When status >= 500 and c.Errors is non-empty, fields already contains zap.String("error", last.Error()), and then Error(msg, ginErr, fields...) appends another field via zap.Error(ginErr) — both use the key error. The emitted line ends up with two error keys (duplicate keys in the JSON-ingested form), which complicates downstream parsing.

Consider only attaching the sentinel through Error and letting c.Errors flow through ginErr, or use a distinct key for the c.Errors string.

♻️ One option
 		var ginErr error
 		if len(c.Errors) > 0 {
 			last := c.Errors.Last()
-			fields = append(fields, zap.String("error", last.Error()))
 			ginErr = last.Err
+			if ginErr == nil {
+				ginErr = errors.New(last.Error())
+			}
 		}
🤖 Prompt for 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.

In `@internal/common/logger.go` around lines 288 - 304, The duplicate error field
occurs because when `status >= 500` and `len(c.Errors) > 0`, the code appends
`zap.String("error", last.Error())` to fields, and then the `Error(msg, ginErr,
fields...)` call adds another error field via `zap.Error(ginErr)`, both using
the "error" key. Remove the `zap.String("error", last.Error())` line from the
fields population block, and instead assign `ginErr = last.Err` so the actual
error object flows through the `Error()` call, resulting in a single "error"
field in the log output rather than duplicate keys.

99-163: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Init never returns a non-nil error.

The only error source (parseZapLevel) is swallowed with a fallback to InfoLevel, so Init always returns nil. Every call site guards if err := common.Init(...); err != nil, which is now dead. Either propagate the parse error (and drop the silent fallback) or change the signature to not return error to avoid misleading callers.

🤖 Prompt for 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.

In `@internal/common/logger.go` around lines 99 - 163, The Init function declares
a return type of error but always returns nil because errors from parseZapLevel
are silently swallowed and replaced with a fallback to InfoLevel. This creates
dead code at all call sites that check for errors. Resolve this by either
removing the error return type from the Init function signature entirely if the
graceful degradation to InfoLevel is the intended behavior, or remove the
fallback logic and propagate the error from parseZapLevel so that invalid log
levels are treated as actual failures that callers can handle appropriately.
internal/handler/system.go (1)

215-222: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Response level may differ from stored/queried level due to normalization.

config.Log.Level is set from common.GetLevel() (normalized, e.g. warn), while the response returns the raw req.Level (e.g. warning or mixed case). A subsequent GetLogLevel would then report a different string than this PUT response echoed. Consider returning common.GetLevel() in data for consistency.

♻️ Proposed tweak
 	c.JSON(http.StatusOK, gin.H{
 		"code":    0,
 		"message": "success",
-		"data":    gin.H{"level": req.Level},
+		"data":    gin.H{"level": common.GetLevel()},
 	})
🤖 Prompt for 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.

In `@internal/handler/system.go` around lines 215 - 222, The response is returning
the raw input value req.Level in the data field, but the actual stored log level
is normalized through common.GetLevel(). This creates an inconsistency where the
response echoes a different format than what was actually stored and what would
be returned by a subsequent GetLogLevel query. Replace req.Level with
common.GetLevel() in the gin.H data field of the JSON response to ensure the
response accurately reflects the normalized log level that was actually
persisted in config.Log.Level.
internal/agent/component/universe_a_wrappers.go (1)

440-443: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Avoid logging full CodeExec payload bodies in debug logs.

These fields can carry user code, arguments, and response content. Prefer redacted metadata (keys/counts/sizes) to reduce sensitive-data exposure and log bloat.

🔧 Suggested pattern
-	common.Debug("CodeExec wrapper invoke",
-		zap.Any("params", c.params),
-		zap.Any("inputs", inputs),
-		zap.Any("merged", merged))
+	common.Debug("CodeExec wrapper invoke",
+		zap.Int("params_keys", len(c.params)),
+		zap.Int("inputs_keys", len(inputs)),
+		zap.Int("merged_keys", len(merged)))

Also applies to: 488-492

🤖 Prompt for 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.

In `@internal/agent/component/universe_a_wrappers.go` around lines 440 - 443, The
debug logging in the CodeExec wrapper invoke call is exposing sensitive data by
logging full payload bodies through the params, inputs, and merged fields.
Instead of logging these complete payloads with zap.Any, refactor the
common.Debug call to log only redacted metadata such as the keys present, count
of items, or sizes of the payloads. Apply the same redaction approach to the
second occurrence of this pattern that also applies to lines around 488-492 to
ensure consistent handling of sensitive data across all CodeExec-related debug
logs.
🤖 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/server_main.go`:
- Line 330: The request logging middleware common.GinLogger() is being
registered twice: once in the startServer function in cmd/server_main.go at line
330 via ginEngine.Use(common.GinLogger()), and again in the (*Router).Setup
method in internal/router/router.go, causing each request to be logged twice.
Remove the common.GinLogger() registration from the startServer function in
cmd/server_main.go and keep only the registration in the (*Router).Setup method
to maintain a single logging point for all incoming requests.

In `@internal/agent/component/llm_credentials.go`:
- Line 68: The code is logging raw API keys in the common.Debug call using
zap.String("api_key", apiKey), which exposes sensitive tenant secrets in
centralized logs. Replace the zap.String("api_key", apiKey) parameter with a
redacted or boolean marker (such as zap.Bool("api_key_present", true)) that
indicates the key exists without exposing the actual value. Apply this change to
both locations where this pattern appears in the LLM credentials resolution
logic (around line 68 and lines 124-128).

In `@internal/agent/tool/code_exec.go`:
- Around line 155-159: The CodeExec tool invoke debug logging is emitting full
raw script and arguments content which may contain sensitive credentials or user
data. In the common.Debug call for "CodeExec tool invoke", replace the
zap.String("script", req.Script) with bounded metadata like the script length or
hash, and replace zap.Any("arguments", req.Arguments) with metadata about the
arguments (such as count or size) instead of the full content. Apply the same
approach to the logging at lines 222-229 where stdout and stderr are logged,
replacing full output content with bounded metadata like output lengths or
hashes instead of raw output values.

In `@internal/handler/system.go`:
- Around line 193-196: The comment block describing the PkgName field in the
struct binding (around lines 193-196) incorrectly states that the field must be
present in the JSON payload for the client to call the endpoint. Since the
PkgName field no longer has binding:"required" (as shown on line 184) and the
CLI client only sends the level field, update the comment to accurately reflect
that only the level field is required in the JSON payload and that PkgName is
optional. Remove the false claim about PkgName being mandatory for the endpoint
call.

In `@internal/router/router.go`:
- Line 126: The common.GinLogger() middleware is currently logging raw query
strings which can expose sensitive authorization parameters like codes and state
tokens in persisted logs. Modify the common.GinLogger() function to exclude
RawQuery from the logged path, and instead log only the clean path without query
parameters, ensuring sensitive OAuth callback parameters and other sensitive
query data are not persisted in access logs.

---

Nitpick comments:
In `@internal/agent/canvas/compile.go`:
- Line 120: The decoder-bypass guard log message in the canvas compile function
should be logged at the Warn level instead of Info level to ensure it appears in
production configurations with warn-level logging. Replace the common.Info call
with common.Warn in the statement that logs the message about legacy
LoopItem/IterationItem/Iteration nodes being received, keeping all the existing
parameters and message content unchanged.

In `@internal/agent/component/universe_a_wrappers.go`:
- Around line 440-443: The debug logging in the CodeExec wrapper invoke call is
exposing sensitive data by logging full payload bodies through the params,
inputs, and merged fields. Instead of logging these complete payloads with
zap.Any, refactor the common.Debug call to log only redacted metadata such as
the keys present, count of items, or sizes of the payloads. Apply the same
redaction approach to the second occurrence of this pattern that also applies to
lines around 488-492 to ensure consistent handling of sensitive data across all
CodeExec-related debug logs.

In `@internal/common/logger.go`:
- Around line 46-49: The comment in the LogConfig documentation block references
a helper function as "resolveCompress" but the actual exported function name is
"ResolveCompress" with a capital R. Update the comment to use the correct
function name "ResolveCompress" so that it matches the actual implementation and
improves grep-ability for developers looking for references to this helper.
- Around line 288-304: The duplicate error field occurs because when `status >=
500` and `len(c.Errors) > 0`, the code appends `zap.String("error",
last.Error())` to fields, and then the `Error(msg, ginErr, fields...)` call adds
another error field via `zap.Error(ginErr)`, both using the "error" key. Remove
the `zap.String("error", last.Error())` line from the fields population block,
and instead assign `ginErr = last.Err` so the actual error object flows through
the `Error()` call, resulting in a single "error" field in the log output rather
than duplicate keys.
- Around line 99-163: The Init function declares a return type of error but
always returns nil because errors from parseZapLevel are silently swallowed and
replaced with a fallback to InfoLevel. This creates dead code at all call sites
that check for errors. Resolve this by either removing the error return type
from the Init function signature entirely if the graceful degradation to
InfoLevel is the intended behavior, or remove the fallback logic and propagate
the error from parseZapLevel so that invalid log levels are treated as actual
failures that callers can handle appropriately.

In `@internal/handler/system.go`:
- Around line 215-222: The response is returning the raw input value req.Level
in the data field, but the actual stored log level is normalized through
common.GetLevel(). This creates an inconsistency where the response echoes a
different format than what was actually stored and what would be returned by a
subsequent GetLogLevel query. Replace req.Level with common.GetLevel() in the
gin.H data field of the JSON response to ensure the response accurately reflects
the normalized log level that was actually persisted in config.Log.Level.
🪄 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: 130ea46c-b688-40a5-b494-b583f3db58ed

📥 Commits

Reviewing files that changed from the base of the PR and between d8ee1ff and 99a81e4.

⛔ 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/server_main.go
if config.Server.Mode == "debug" {
ginEngine.Use(gin.Logger())
}
ginEngine.Use(common.GinLogger())

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.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Avoid double-registration of request logging middleware.

startServer registers common.GinLogger() here, and internal/router/router.go registers it again in (*Router).Setup. Each request gets logged twice, inflating log volume and noise.

Suggested fix (keep a single registration point)
-	ginEngine.Use(common.GinLogger())
 	ginEngine.Use(gin.Recovery())
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ginEngine.Use(common.GinLogger())
ginEngine.Use(gin.Recovery())
🤖 Prompt for 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.

In `@cmd/server_main.go` at line 330, The request logging middleware
common.GinLogger() is being registered twice: once in the startServer function
in cmd/server_main.go at line 330 via ginEngine.Use(common.GinLogger()), and
again in the (*Router).Setup method in internal/router/router.go, causing each
request to be logged twice. Remove the common.GinLogger() registration from the
startServer function in cmd/server_main.go and keep only the registration in the
(*Router).Setup method to maintain a single logging point for all incoming
requests.

baseURL = *row.APIBase
}
log.Printf("DEBUG llm credentials: tenant_llm OK api_key=%q base_url=%q", apiKey, baseURL)
common.Debug("llm credentials: tenant_llm OK", zap.String("api_key", apiKey), zap.String("base_url", baseURL))

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not log raw API keys from credential resolution paths.

zap.String("api_key", apiKey) leaks tenant secrets into centralized logs. Replace with a redacted/boolean marker only.

🔧 Proposed fix
-	common.Debug("llm credentials: tenant_llm OK", zap.String("api_key", apiKey), zap.String("base_url", baseURL))
+	common.Debug("llm credentials: tenant_llm OK",
+		zap.Bool("api_key_present", apiKey != ""),
+		zap.String("base_url", baseURL))
...
-	common.Debug("llm credentials: new-table OK",
-		zap.String("provider", providerName),
-		zap.String("instance", instance.InstanceName),
-		zap.String("api_key", apiKey),
-		zap.String("base_url", baseURL))
+	common.Debug("llm credentials: new-table OK",
+		zap.String("provider", providerName),
+		zap.String("instance", instance.InstanceName),
+		zap.Bool("api_key_present", apiKey != ""),
+		zap.String("base_url", baseURL))

Also applies to: 124-128

🤖 Prompt for 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.

In `@internal/agent/component/llm_credentials.go` at line 68, The code is logging
raw API keys in the common.Debug call using zap.String("api_key", apiKey), which
exposes sensitive tenant secrets in centralized logs. Replace the
zap.String("api_key", apiKey) parameter with a redacted or boolean marker (such
as zap.Bool("api_key_present", true)) that indicates the key exists without
exposing the actual value. Apply this change to both locations where this
pattern appears in the LLM credentials resolution logic (around line 68 and
lines 124-128).

Comment on lines +155 to +159
common.Debug("CodeExec tool invoke",
zap.String("lang", req.Lang),
zap.Int("timeout", req.Timeout),
zap.Any("arguments", req.Arguments),
zap.String("script", req.Script))

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not emit raw code and full execution output to logs.

script, arguments, stdout, and stderr may contain credentials or sensitive user data. Log bounded metadata (lengths/hashes/flags) instead of full content.

🔧 Proposed fix
 	common.Debug("CodeExec tool invoke",
 		zap.String("lang", req.Lang),
 		zap.Int("timeout", req.Timeout),
-		zap.Any("arguments", req.Arguments),
-		zap.String("script", req.Script))
+		zap.Int("arguments_keys", len(req.Arguments)),
+		zap.Int("script_len", len(req.Script)))

 	common.Debug("CodeExec tool",
 		zap.Any("structured_result", r.StructuredResult),
 		zap.Any("resolved_value", resolvedValue),
 		zap.Any("raw_result", out.RawResult),
-		zap.String("content", out.Content),
 		zap.String("actual_type", out.ActualType),
-		zap.String("stderr", r.Stderr),
-		zap.String("stdout", r.Stdout))
+		zap.Int("content_len", len(out.Content)),
+		zap.Bool("has_stderr", strings.TrimSpace(r.Stderr) != ""),
+		zap.Int("stdout_len", len(r.Stdout)))

Also applies to: 222-229

🤖 Prompt for 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.

In `@internal/agent/tool/code_exec.go` around lines 155 - 159, The CodeExec tool
invoke debug logging is emitting full raw script and arguments content which may
contain sensitive credentials or user data. In the common.Debug call for
"CodeExec tool invoke", replace the zap.String("script", req.Script) with
bounded metadata like the script length or hash, and replace
zap.Any("arguments", req.Arguments) with metadata about the arguments (such as
count or size) instead of the full content. Apply the same approach to the
logging at lines 222-229 where stdout and stderr are logged, replacing full
output content with bounded metadata like output lengths or hashes instead of
raw output values.

Comment on lines +193 to +196
// Go side `pkg_name` is no longer required (per-package filtering
// is gone), but the message wording is unchanged for backward
// compatibility — the field still has to be present in the JSON
// payload for the client to call this endpoint at all.

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Doc comment contradicts the actual binding.

PkgName no longer carries binding:"required" (Line 184), and the CLI client sends only {"level": ...} (per internal/cli/user_command.go). So the claim that "the field still has to be present in the JSON payload for the client to call this endpoint at all" is incorrect — only level is required. Please correct the comment to avoid confusion.

🤖 Prompt for 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.

In `@internal/handler/system.go` around lines 193 - 196, The comment block
describing the PkgName field in the struct binding (around lines 193-196)
incorrectly states that the field must be present in the JSON payload for the
client to call the endpoint. Since the PkgName field no longer has
binding:"required" (as shown on line 184) and the CLI client only sends the
level field, update the comment to accurately reflect that only the level field
is required in the JSON payload and that PkgName is optional. Remove the false
claim about PkgName being mandatory for the endpoint call.

Comment thread internal/router/router.go

// Log all HTTP requests.
engine.Use(gin.Logger())
engine.Use(common.GinLogger())

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not log raw query strings in access logs.

common.GinLogger() appends RawQuery to the logged path. On routes like OAuth callbacks, this can leak authorization codes/state (and other sensitive params) into persisted logs.

🤖 Prompt for 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.

In `@internal/router/router.go` at line 126, The common.GinLogger() middleware is
currently logging raw query strings which can expose sensitive authorization
parameters like codes and state tokens in persisted logs. Modify the
common.GinLogger() function to exclude RawQuery from the logged path, and
instead log only the clean path without query parameters, ensuring sensitive
OAuth callback parameters and other sensitive query data are not persisted in
access logs.

@yuzhichang yuzhichang closed this Jun 23, 2026
@yuzhichang
yuzhichang deleted the agent-go-port branch June 23, 2026 06:58
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 23, 2026
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]>
@yuzhichang

Copy link
Copy Markdown
Member Author

Closing this PR — see #16261 for the follow-up. Same head branch (yuzhichang:agent-go-port), same parent commit (296c0b733 Unified log), with dfd946d54 adding the 5 CodeRabbit review fixes on top.

CodeRabbit review resolutions (all 5 applied in dfd946d54)

File Review comment Resolution
cmd/server_main.go:330 Duplicate common.GinLogger() registration (also registered inside router.Setup) Removed local registration; Setup owns it. Replaced with an inline comment explaining why.
internal/agent/component/llm_credentials.go:68 + :124-128 zap.String("api_key", apiKey) leaks API keys Replaced with zap.Bool("api_key_present", apiKey != "") in both tenant_llm OK and new-table OK debug log sites.
internal/agent/tool/code_exec.go:159 + :222-229 Raw script / arguments / stdout / stderr may carry credentials Bound to script_len, arguments_keys, stdout_len, stderr_len + stderr_present flag.
internal/router/router.go:126 (common.GinLogger) Logs raw query string (OAuth codes / SAML responses / signed state) Drop query from the path field; record has_query (bool) and query_len (int) instead so operators can still see that one was sent.
internal/handler/system.go:196 Doc comment claimed pkg_name was required, but binding only enforces level Corrected the comment. The "pkg_name and level are required" error message text is preserved verbatim for backward compatibility with clients that match on it.

Verification

bash build.sh --go    # all 4 binaries built
bash build.sh --test  # all packages pass; zero failures

Re: the force-push race

I noticed #16260 was closed at 2026-06-23T06:58:13Z with a head_ref_deleted event around the same time my git push got "stale info" — likely a race between my push attempt and the branch deletion. GitHub's API then refused to reopen the PR (HTTP 422: "state cannot be changed. The agent-go-port branch was force-pushed or recreated"), and the update-branch endpoint refused because the stored head SHA (99a81e4ce) no longer matched the fork tip. Opening a fresh PR was the cleanest way out.

yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 23, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code 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