Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(cli): persist daemon log level per profile (MUL-9728) (#11068)

Danila Katalshovc90de431fc26
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 15d3ddd3f1..2a2caac250 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -379,6 +379,7 @@ Daemon behavior is configured via flags or environment variables:
| Poll interval | `--poll-interval` | `MULTICA_DAEMON_POLL_INTERVAL` | `30s` (catch-up fallback; WebSocket wake signals deliver work sooner) |
| Healthy WebSocket claim poll upper bound | `--ws-claim-poll-interval` | `MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL` | `3m` (configured independently of `--poll-interval`; downward jitter makes the normal interval `2m30s`–`2m45s`, while old servers and uncertain claims retain the ordinary poll interval) |
| Heartbeat interval | `--heartbeat-interval` | `MULTICA_DAEMON_HEARTBEAT_INTERVAL` | `15s` |
+| Daemon log level | — | `LOG_LEVEL` | `debug` |
| Agent timeout | `--agent-timeout` | `MULTICA_AGENT_TIMEOUT` | `0` (no cap; bounded by the watchdogs) |
| Agent idle watchdog | — | `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` (`0` disables the whole watchdog suite) |
| Agent tool watchdog | — | `MULTICA_AGENT_TOOL_WATCHDOG` | same as the idle watchdog (`0` = never force-stop during a tool call) |
diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdx
index 1c36d968c9..74b81597f2 100644
--- a/apps/docs/content/docs/environment-variables.fr.mdx
+++ b/apps/docs/content/docs/environment-variables.fr.mdx
@@ -283,6 +283,8 @@ Le daemon nettoie régulièrement les répertoires des exécutions, les caches d
### Journaux du daemon [#daemon-logs]
+Le daemon journalise au niveau `debug` par défaut. Définissez `LOG_LEVEL` (`debug`, `info`, `warn` ou `error`) pour le changer, ou enregistrez une valeur par défaut pour le profil avec `multica config set log_level info`. La variable d’environnement est prioritaire sur le profil.
+
Quand le daemon tourne en arrière-plan (sans terminal attaché), il écrit ses journaux dans `~/.multica/daemon.log`, ou `~/.multica/profiles/<name>/daemon.log` pour un profil nommé, avec une rotation par taille ; les fichiers issus de la rotation sont compressés en gzip.
| Variable | Valeur par défaut | Description |
@@ -385,6 +387,7 @@ Clés prises en charge :
| `poll_interval` | `30s` | Intervalle d'interrogation des exécutions |
| `ws_claim_poll_interval` | `3m` | Borne supérieure des interrogations de sécurité de la prise en charge via WebSocket lorsque celle-ci est saine, indépendante de `poll_interval` ; le daemon applique une gigue uniquement à la baisse |
| `heartbeat_interval` | `15s` | Intervalle des signaux de vie (heartbeat) |
+| `log_level` | `debug` | Niveau des journaux du daemon : `debug`, `info`, `warn` ou `error`. `LOG_LEVEL` est prioritaire |
| `agent_timeout` | illimité | Durée maximale absolue par exécution |
| `agent_idle_watchdog` | `2h` | Durée maximale de silence lorsqu'aucun appel d'outil n'est en cours ; `0s` désactive entièrement le watchdog du daemon, y compris `agent_tool_watchdog` |
| `agent_tool_watchdog` | identique à `agent_idle_watchdog` | Durée maximale de silence pendant un appel d'outil ; avec `0s`, le watchdog du daemon n'arrête jamais une exécution à cause d'un appel d'outil silencieux, et l'exécution n'est plus bornée que par `agent_timeout`, illimité par défaut |
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 46f2372e2b..06ce8a67e4 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -286,6 +286,8 @@ API key と base URL の両方が空の場合、このレイヤーは無効に
### デーモンのログ [#daemon-logs]
+デーモンの既定のログレベルは `debug` です。変更するには `LOG_LEVEL`(`debug`、`info`、`warn`、`error`)を設定するか、`multica config set log_level info` でプロファイルの既定値を保存します。環境変数がプロファイルより優先されます。
+
デーモンがバックグラウンドで(ターミナルにつながずに)動いているとき、ログは `~/.multica/daemon.log`(名前付きプロファイルでは `~/.multica/profiles/<name>/daemon.log`)に書かれ、サイズでローテーションされます。ローテーション後のファイルは gzip で圧縮されます。
| 変数 | デフォルト | 説明 |
@@ -388,6 +390,7 @@ multica config show
| `poll_interval` | `30s` | 実行のポーリング間隔 |
| `ws_claim_poll_interval` | `3m` | 正常な WebSocket での claim 安全ポーリング上限。`poll_interval` とは独立して設定され、Daemon は下方向のジッターを適用します |
| `heartbeat_interval` | `15s` | ハートビート間隔 |
+| `log_level` | `debug` | デーモンのログレベル(`debug`、`info`、`warn`、`error`)。`LOG_LEVEL` が優先されます |
| `agent_timeout` | 無制限 | 1 回の実行の絶対時間上限 |
| `agent_idle_watchdog` | `2h` | ツール実行中でないときの静穏上限。`0s` でデーモンの watchdog 全体を無効化し、`agent_tool_watchdog` も効かなくなります |
| `agent_tool_watchdog` | `agent_idle_watchdog` と同じ | ツール実行中の静穏上限。`0s` にするとデーモンの watchdog は静穏なツール呼び出しを理由に実行を停止しなくなり、実行の上限は `agent_timeout`(デフォルトは無制限)だけになります |
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 78a8d5353a..094493e4b8 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -286,6 +286,8 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스
### 데몬 로그 [#daemon-logs]
+데몬의 기본 로그 수준은 `debug`입니다. 바꾸려면 `LOG_LEVEL`(`debug`, `info`, `warn`, `error`)을 설정하거나 `multica config set log_level info`로 프로필 기본값을 저장합니다. 환경 변수가 프로필보다 우선합니다.
+
데몬이 백그라운드에서(터미널에 연결되지 않은 채) 실행될 때 로그는 `~/.multica/daemon.log`(이름 있는 프로필은 `~/.multica/profiles/<name>/daemon.log`)에 기록되고 크기에 따라 순환됩니다. 순환된 파일은 gzip으로 압축됩니다.
| 변수 | 기본값 | 설명 |
@@ -388,6 +390,7 @@ multica config show
| `poll_interval` | `30s` | 실행 polling 간격 |
| `ws_claim_poll_interval` | `3m` | 정상 WebSocket에서 claim 안전 polling의 상한. `poll_interval`과 독립적으로 설정되며 Daemon은 하향 jitter를 적용합니다 |
| `heartbeat_interval` | `15s` | heartbeat 간격 |
+| `log_level` | `debug` | 데몬 로그 수준(`debug`, `info`, `warn`, `error`). `LOG_LEVEL`이 우선함 |
| `agent_timeout` | 제한 없음 | 단일 실행의 절대 시간 제한 |
| `agent_idle_watchdog` | `2h` | 실행 중인 도구 호출이 없을 때의 무응답 상한. `0s`이면 데몬 watchdog 전체가 꺼지며 `agent_tool_watchdog`도 적용되지 않습니다 |
| `agent_tool_watchdog` | `agent_idle_watchdog`와 동일 | 도구 호출이 실행 중일 때의 무응답 상한. `0s`이면 데몬 watchdog이 무응답 도구 호출 때문에 실행을 멈추지 않으며, 실행은 `agent_timeout`(기본값은 제한 없음)으로만 제한됩니다 |
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 7dfb569338..60a7a485df 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -292,6 +292,8 @@ The daemon periodically cleans up run directories, repository caches, session re
### Daemon logs [#daemon-logs]
+The daemon logs at `debug` by default. Set `LOG_LEVEL` (`debug`, `info`, `warn` or `error`) to change it, or save a profile default with `multica config set log_level info`. The environment variable overrides the profile.
+
When the daemon runs in the background (not attached to a terminal), it writes logs to `~/.multica/daemon.log`, or `~/.multica/profiles/<name>/daemon.log` for a named profile, rotating by size and compressing rotated files with gzip.
| Variable | Default | Description |
@@ -394,6 +396,7 @@ Supported keys:
| `poll_interval` | `30s` | Run polling interval |
| `ws_claim_poll_interval` | `3m` | Upper bound for healthy WebSocket claim safety polls, independent of `poll_interval`; the daemon applies downward-only jitter |
| `heartbeat_interval` | `15s` | Heartbeat interval |
+| `log_level` | `debug` | Daemon log level: `debug`, `info`, `warn` or `error`. `LOG_LEVEL` overrides it |
| `agent_timeout` | unlimited | Absolute time limit per run |
| `agent_idle_watchdog` | `2h` | Silence ceiling when no tool call is in flight; `0s` turns off the daemon watchdog entirely, including `agent_tool_watchdog` |
| `agent_tool_watchdog` | same as `agent_idle_watchdog` | Silence ceiling while a tool call is in flight; `0s` means the daemon watchdog never stops a run over a silent tool call, so the run is bounded only by `agent_timeout`, which is unlimited by default |
diff --git a/apps/docs/content/docs/environment-variables.zh-Hant.mdx b/apps/docs/content/docs/environment-variables.zh-Hant.mdx
index edfe792239..c14f9669dd 100644
--- a/apps/docs/content/docs/environment-variables.zh-Hant.mdx
+++ b/apps/docs/content/docs/environment-variables.zh-Hant.mdx
@@ -282,6 +282,8 @@ API key 與 base URL 都為空時,這一層關閉,不會發出任何上游
### 守護程序日誌 [#daemon-logs]
+守護程序預設以 `debug` 層級寫入日誌。設定 `LOG_LEVEL`(`debug`、`info`、`warn` 或 `error`)可以修改,也可以用 `multica config set log_level info` 儲存設定檔的預設值。環境變數優先於設定檔。
+
守護程序在後臺執行(不連著終端)時,日誌寫入 `~/.multica/daemon.log`,命名 profile 為 `~/.multica/profiles/<name>/daemon.log`,並按大小輪轉,輪轉出的檔案用 gzip 壓縮。
| 變數 | 預設值 | 說明 |
@@ -384,6 +386,7 @@ multica config show
| `poll_interval` | `30s` | 執行輪詢間隔 |
| `ws_claim_poll_interval` | `3m` | 健康 WebSocket 下 claim 安全輪詢的上限,與 `poll_interval` 獨立配置;Daemon 會應用向下抖動 |
| `heartbeat_interval` | `15s` | 心跳間隔 |
+| `log_level` | `debug` | 守護程序日誌層級:`debug`、`info`、`warn` 或 `error`。`LOG_LEVEL` 優先 |
| `agent_timeout` | 不限制 | 單次執行的絕對時限 |
| `agent_idle_watchdog` | `2h` | 沒有工具執行時的靜默上限;`0s` 關閉守護程序的整套 watchdog,`agent_tool_watchdog` 也隨之失效 |
| `agent_tool_watchdog` | 同 `agent_idle_watchdog` | 工具執行期間的靜默上限;`0s` 表示守護程序的 watchdog 不會因工具靜默而停止執行,此時執行只受 `agent_timeout` 限制,而它預設不限制 |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 2fe70a34c5..45296ed438 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -286,6 +286,8 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游
### 守护进程日志 [#daemon-logs]
+守护进程默认按 `debug` 级别写日志。设置 `LOG_LEVEL`(`debug`、`info`、`warn` 或 `error`)可以修改,也可以用 `multica config set log_level info` 保存配置档案的默认值。环境变量优先于配置档案。
+
守护进程在后台运行(不连着终端)时,日志写入 `~/.multica/daemon.log`,命名 profile 为 `~/.multica/profiles/<name>/daemon.log`,并按大小轮转,轮转出的文件用 gzip 压缩。
| 变量 | 默认值 | 说明 |
@@ -388,6 +390,7 @@ multica config show
| `poll_interval` | `30s` | 运行轮询间隔 |
| `ws_claim_poll_interval` | `3m` | 健康 WebSocket 下 claim 安全轮询的上限,与 `poll_interval` 独立配置;Daemon 会应用向下抖动 |
| `heartbeat_interval` | `15s` | 心跳间隔 |
+| `log_level` | `debug` | 守护进程日志级别:`debug`、`info`、`warn` 或 `error`。`LOG_LEVEL` 优先 |
| `agent_timeout` | 不限制 | 单次执行的绝对时限 |
| `agent_idle_watchdog` | `2h` | 没有工具执行时的静默上限;`0s` 关闭守护进程的整套 watchdog,`agent_tool_watchdog` 也随之失效 |
| `agent_tool_watchdog` | 同 `agent_idle_watchdog` | 工具执行期间的静默上限;`0s` 表示守护进程的 watchdog 不会因工具静默而停止执行,此时执行只受 `agent_timeout` 限制,而它默认不限制 |
diff --git a/server/cmd/multica/cmd_config.go b/server/cmd/multica/cmd_config.go
index 00a09c224c..e11c103577 100644
--- a/server/cmd/multica/cmd_config.go
+++ b/server/cmd/multica/cmd_config.go
@@ -39,6 +39,7 @@ var configSetSupportedKeys = []string{
"poll_interval",
"ws_claim_poll_interval",
"heartbeat_interval",
+ "log_level",
"agent_timeout",
"agent_idle_watchdog",
"agent_tool_watchdog",
@@ -57,7 +58,7 @@ var configSetCmd = &cobra.Command{
"device_name, runtime_name, workspaces_root, max_concurrent_tasks, poll_interval, ws_claim_poll_interval, " +
"heartbeat_interval, agent_timeout, agent_idle_watchdog, agent_tool_watchdog, " +
"codex_semantic_inactivity_timeout, codex_handshake_timeout, " +
- "disable_auto_update, auto_update_check_interval, disable_auto_reload.\n\n" +
+ "disable_auto_update, auto_update_check_interval, disable_auto_reload, log_level.\n\n" +
"The daemon keys (device_name, runtime_name, workspaces_root, max_concurrent_tasks, " +
"poll_interval, ws_claim_poll_interval, heartbeat_interval, agent_timeout, agent_idle_watchdog, agent_tool_watchdog, " +
"codex_semantic_inactivity_timeout, codex_handshake_timeout, " +
@@ -72,7 +73,8 @@ var configSetCmd = &cobra.Command{
"(single-direction: setting one to 'true' turns that behavior off, " +
"'false' clears the override so env/default decides). Pass an empty " +
"string to clear a persisted " +
- "value (e.g. `config set poll_interval \"\"`).",
+ "value (e.g. `config set poll_interval \"\"`). " +
+ "log_level controls daemon logs (debug, info, warn, error). LOG_LEVEL overrides it.",
Args: exactArgs(2),
RunE: runConfigSet,
}
@@ -107,6 +109,7 @@ func runConfigShow(cmd *cobra.Command, _ []string) error {
fmt.Fprintf(os.Stdout, "%-34s %s\n", "poll_interval:", valueOrDefault(cfg.PollInterval, "(not set)"))
fmt.Fprintf(os.Stdout, "%-34s %s\n", "ws_claim_poll_interval:", valueOrDefault(cfg.WSClaimPollInterval, "(not set)"))
fmt.Fprintf(os.Stdout, "%-34s %s\n", "heartbeat_interval:", valueOrDefault(cfg.HeartbeatInterval, "(not set)"))
+ fmt.Fprintf(os.Stdout, "%-34s %s\n", "log_level:", valueOrDefault(cfg.LogLevel, "(not set)"))
fmt.Fprintf(os.Stdout, "%-34s %s\n", "agent_timeout:", agentTimeoutDisplay(cfg.AgentTimeout))
fmt.Fprintf(os.Stdout, "%-34s %s\n", "agent_idle_watchdog:", valueOrDefault(cfg.AgentIdleWatchdog, "(not set)"))
fmt.Fprintf(os.Stdout, "%-34s %s\n", "agent_tool_watchdog:", valueOrDefault(cfg.AgentToolWatchdog, "(not set)"))
@@ -215,6 +218,16 @@ func applyConfigSet(cfg *cli.CLIConfig, key, value string) error {
if err := assignPositiveDuration(&cfg.WSClaimPollInterval, key, value); err != nil {
return err
}
+ case "log_level":
+ // Accept the same spellings LOG_LEVEL does, stored in canonical form.
+ switch level := strings.ToLower(strings.TrimSpace(value)); level {
+ case "", "debug", "info", "warn", "error":
+ cfg.LogLevel = level
+ case "warning":
+ cfg.LogLevel = "warn"
+ default:
+ return fmt.Errorf("log_level must be debug, info, warn, or error (got %q)", value)
+ }
case "heartbeat_interval":
if err := assignPositiveDuration(&cfg.HeartbeatInterval, key, value); err != nil {
return err
diff --git a/server/cmd/multica/cmd_config_test.go b/server/cmd/multica/cmd_config_test.go
index dbd3f2e6e9..18b9d0b794 100644
--- a/server/cmd/multica/cmd_config_test.go
+++ b/server/cmd/multica/cmd_config_test.go
@@ -39,13 +39,16 @@ func TestRunConfigSetPersistsSupportedKeysInProfile(t *testing.T) {
if err := runConfigSet(cmd, []string{"workspaces_root", workspacesRoot}); err != nil {
t.Fatalf("runConfigSet workspaces_root: %v", err)
}
+ if err := runConfigSet(cmd, []string{"log_level", "info"}); err != nil {
+ t.Fatalf("runConfigSet log_level: %v", err)
+ }
_ = stderr.read()
cfg, err := cli.LoadCLIConfigForProfile("dev")
if err != nil {
t.Fatalf("LoadCLIConfigForProfile: %v", err)
}
- if cfg.ServerURL != "http://127.0.0.1:8080" || cfg.AppURL != "http://127.0.0.1:3000" || cfg.WorkspaceID != "ws-123" || cfg.WorkspacesRoot != workspacesRoot {
+ if cfg.ServerURL != "http://127.0.0.1:8080" || cfg.AppURL != "http://127.0.0.1:3000" || cfg.WorkspaceID != "ws-123" || cfg.WorkspacesRoot != workspacesRoot || cfg.LogLevel != "info" {
t.Fatalf("config = %#v, want persisted supported keys", cfg)
}
}
@@ -377,6 +380,7 @@ func TestApplyConfigSetRejectsBadValues(t *testing.T) {
{"ws claim poll zero", "ws_claim_poll_interval", "0s", "positive"},
{"heartbeat bad duration", "heartbeat_interval", "abc", "duration"},
{"heartbeat zero", "heartbeat_interval", "0s", "positive"},
+ {"unknown log level", "log_level", "trace", "debug, info, warn, or error"},
{"codex semantic zero", "codex_semantic_inactivity_timeout", "0s", "positive"},
{"codex handshake bad", "codex_handshake_timeout", "10", "duration"},
{"agent_timeout bad duration", "agent_timeout", "abc", "duration"},
@@ -401,6 +405,22 @@ func TestApplyConfigSetRejectsBadValues(t *testing.T) {
}
}
+// TestApplyConfigSetNormalizesLogLevel keeps config set in step with the
+// spellings LOG_LEVEL already accepts.
+func TestApplyConfigSetNormalizesLogLevel(t *testing.T) {
+ t.Parallel()
+
+ for value, want := range map[string]string{"INFO": "info", " Debug ": "debug", "warning": "warn", "ERROR": "error", "": ""} {
+ cfg := cli.CLIConfig{LogLevel: "info"}
+ if err := applyConfigSet(&cfg, "log_level", value); err != nil {
+ t.Fatalf("applyConfigSet(log_level, %q): %v", value, err)
+ }
+ if cfg.LogLevel != want {
+ t.Fatalf("applyConfigSet(log_level, %q) stored %q, want %q", value, cfg.LogLevel, want)
+ }
+ }
+}
+
// TestApplyConfigSetPollIntervalZeroDoesNotOverwrite ensures a rejected
// "0s" write leaves any previously persisted value intact — the caller
// only saves when applyConfigSet returns nil, but pin the invariant so
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index 5eee86b954..808d54ab8a 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -973,6 +973,7 @@ func runDaemonForeground(cmd *cobra.Command) error {
// than server URL: an unreadable / missing config only means "no
// persisted overrides", not "cannot start".
fileCfg, _ := cli.LoadCLIConfigForProfile(profile)
+ logLevel := resolveDaemonLogLevel(fileCfg.LogLevel)
// Pick the log sink. A user who runs `daemon start --foreground` in a shell
// keeps live, colored logging on their terminal (a documented debugging
// path — see docs troubleshooting). A detached/background child, whose
@@ -984,7 +985,7 @@ func runDaemonForeground(cmd *cobra.Command) error {
logRotator *lumberjack.Logger
)
if logger_pkg.StderrIsTerminal() {
- logger = logger_pkg.NewLogger("daemon")
+ logger = logger_pkg.NewWriterLoggerDefault("daemon", os.Stderr, logLevel, false)
} else {
// An older self-update launcher may have handed this process daemon.log
// itself as stdout/stderr. On Windows that inherited handle lacks
@@ -998,7 +999,7 @@ func runDaemonForeground(cmd *cobra.Command) error {
// Route both this process's structured logger and the package-global
// slog default through the rotator, so every log line — including
// LoadConfig's slog.Warn below — is captured and rotated.
- logger = logger_pkg.NewWriterLoggerDefault("daemon", logRotator)
+ logger = logger_pkg.NewWriterLoggerDefault("daemon", logRotator, logLevel, true)
}
serverURL := resolveDaemonServerURL(cmd, profile)
@@ -1199,7 +1200,7 @@ func runDaemonForeground(cmd *cobra.Command) error {
// including the package-global slog default (which would otherwise
// reopen daemon.log on its next write).
if logRotator != nil {
- logger = logger_pkg.NewWriterLoggerDefault("daemon", os.Stderr)
+ logger = logger_pkg.NewWriterLoggerDefault("daemon", os.Stderr, logLevel, true)
_ = logRotator.Close()
}
@@ -1813,6 +1814,16 @@ func resolveWorkspacesRootForProfile(profile, flagValue string) (string, error)
return daemon.ResolveWorkspacesRoot(profile, override)
}
+// resolveDaemonLogLevel picks the daemon log level: LOG_LEVEL wins when set,
+// otherwise the profile's log_level. An empty result leaves the logger on its
+// built-in default (debug).
+func resolveDaemonLogLevel(cfgValue string) string {
+ if !envUnset("LOG_LEVEL") {
+ return os.Getenv("LOG_LEVEL")
+ }
+ return cfgValue
+}
+
// resolveDaemonDurationOverride is the numeric counterpart for
// poll_interval. flagValue > 0 wins; otherwise, if the env var is unset
// we parse cfgValue. Parse errors and non-positive values are surfaced
diff --git a/server/cmd/multica/cmd_daemon_precedence_test.go b/server/cmd/multica/cmd_daemon_precedence_test.go
index 4730696c3c..bfac2da344 100644
--- a/server/cmd/multica/cmd_daemon_precedence_test.go
+++ b/server/cmd/multica/cmd_daemon_precedence_test.go
@@ -351,3 +351,26 @@ func TestResolveDaemonDisableSignalPrecedence(t *testing.T) {
})
}
}
+
+// TestResolveDaemonLogLevelPrecedence pins LOG_LEVEL > profile log_level.
+func TestResolveDaemonLogLevelPrecedence(t *testing.T) {
+ cases := []struct {
+ name string
+ env string
+ cfg string
+ want string
+ }{
+ {"env wins over cfg", "error", "info", "error"},
+ {"cfg used when env unset", "", "info", "info"},
+ {"whitespace env counts as unset", " ", "warn", "warn"},
+ {"all unset returns empty", "", "", ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("LOG_LEVEL", tc.env)
+ if got := resolveDaemonLogLevel(tc.cfg); got != tc.want {
+ t.Fatalf("resolveDaemonLogLevel(%q) with LOG_LEVEL=%q = %q, want %q", tc.cfg, tc.env, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/cli/config.go b/server/internal/cli/config.go
index af59f70e44..9ff38a1b1f 100644
--- a/server/internal/cli/config.go
+++ b/server/internal/cli/config.go
@@ -91,6 +91,8 @@ type CLIConfig struct {
// DefaultHeartbeatInterval.
HeartbeatInterval string `json:"heartbeat_interval,omitempty"`
+ LogLevel string `json:"log_level,omitempty"`
+
// AgentTimeout is the absolute wall-clock cap per agent run (Go
// duration string). Unlike the other duration knobs, "0s" is a
// meaningful, non-default value here: it explicitly disables the cap
diff --git a/server/internal/logger/logger.go b/server/internal/logger/logger.go
index 3b9c86c8ab..28fb2da11e 100644
--- a/server/internal/logger/logger.go
+++ b/server/internal/logger/logger.go
@@ -59,19 +59,14 @@ func StderrIsTerminal() bool {
return isTerminal(os.Stderr)
}
-// NewWriterLoggerDefault builds a named slog logger that writes structured,
-// color-free output to w, and installs the same handler as the global slog
+// NewWriterLoggerDefault builds a named slog logger that writes structured output to w, and installs the same handler as the global slog
// default so bare slog.Info/Warn/... calls (e.g. from LoadConfig) land in the
-// same sink. Intended for standalone processes that log to a file or rotating
-// writer instead of a terminal (the daemon), where ANSI color is never wanted
-// and every log line — injected-logger and package-global alike — must end up
-// in the one managed file. Reads LOG_LEVEL like NewLogger/Init.
-func NewWriterLoggerDefault(component string, w io.Writer) *slog.Logger {
- level := parseLevel(os.Getenv("LOG_LEVEL"))
+// same sink. Pass noColor for a file or rotating writer.
+func NewWriterLoggerDefault(component string, w io.Writer, level string, noColor bool) *slog.Logger {
handler := tint.NewHandler(w, &tint.Options{
- Level: level,
+ Level: parseLevel(level),
TimeFormat: "15:04:05.000",
- NoColor: true,
+ NoColor: noColor,
})
base := slog.New(handler)
slog.SetDefault(base)
diff --git a/server/internal/logger/logger_test.go b/server/internal/logger/logger_test.go
index c6466ccd54..d5af6a2dff 100644
--- a/server/internal/logger/logger_test.go
+++ b/server/internal/logger/logger_test.go
@@ -18,12 +18,17 @@ func TestNewWriterLoggerDefault(t *testing.T) {
t.Cleanup(func() { slog.SetDefault(prev) })
var buf bytes.Buffer
- log := NewWriterLoggerDefault("daemon", &buf)
+ log := NewWriterLoggerDefault("daemon", &buf, "info", true)
+ log.Debug("component-debug")
+ slog.Debug("global-debug")
log.Error("boom", "code", 42)
slog.Warn("global-line")
out := buf.String()
+ if strings.Contains(out, "-debug") {
+ t.Errorf("debug messages reached an info-level writer: %q", out)
+ }
if !strings.Contains(out, "boom") {
t.Errorf("component logger output missing message: %q", out)
}