feat(logging): add safe hot-reloadable rotating file sink (#116)

This commit is contained in:
Jason Xu committed 2026-11-30 04:40:43 +08:00
1 parent 9b44a031ca
commit 30d6c08a9c
15 files changed
+338 -19

No files matched your search

+2
View File
@@ -7,6 +7,8 @@ opencode/
/opencode2api
/opencode2api.exe
*.log
*.log.*
logs/
.tmp/
.gocache/
*.models.catalog.json
+3 -1
View File
@@ -277,7 +277,7 @@ Configuration saves validate and construct a replacement runtime before applying
| Model and metadata caches | `config.json.models.catalog.json`, `config.json.models.dev.json`. |
| Availability and rotation | `config.json.<upstream-fingerprint>.availability.json`, `config.json.rotation.json`. |
| Sessions, usage, recent requests/attempts, log ring, last Playground result | Memory; reset on process restart. |
| Structured logs | JSON on stdout; retention requires an external collector. |
| Structured logs | JSON on stdout; optional `logging.file_path` mirrors them to disk with one `.1` backup. |
Names use the actual configuration path. Monitoring survives hot reloads but is not shared across processes. Token counts use upstream-reported usage; missing usage is not estimated. Request completion and upstream header-attempt metrics measure different things. Playground has a separate usage bucket. The recent-hour buffers retain at most 10,000 requests/20,000 attempts and return at most 500 of each.
@@ -287,6 +287,8 @@ Keep API and management listeners on loopback for local use. For network access,
Configuration files and backups hold upstream keys, proxy passwords, and OAuth tokens; password hashing does not encrypt them. Restrict filesystem permissions (Windows ACLs when applicable) and exclude runtime files from source sharing. `logging.dump_request_bodies` is off by default and requires debug logging; even redacted, capped body dumps can reveal conversation content. Playground and availability probes send real upstream requests and can consume quota or credits.
`logging.file_path` defaults to empty (disabled) and can be changed in the logging settings without restarting. Relative paths resolve beside the configuration file and stay relative when saved. The file receives the same redacted JSON records as stdout and rotates at record boundaries around 32 MiB to `<path>.1`, retaining one backup; one oversized record may exceed the threshold. Open or rotation failures do not stop console/in-memory logging; a failed retarget keeps the previous sink. Files use mode `0600` where supported; restrict Windows ACLs separately. Request-body dumps can still contain sensitive conversation text, and file appends do not guarantee durability through an operating-system or power failure.
## Local development and verification
`cmd/opencode2api` starts the service. `internal/admin` owns management, `gateway` owns routing/runtime, `protocol` handles JSON/SSE conversion, `models` owns discovery, `oauth` owns official authorization, `config` owns validation/persistence, and `telemetry` owns metrics/logging. Static assets live in `webui`; no frontend package installation is required.
+3 -1
View File
@@ -275,7 +275,7 @@ API Key 页面支持创建、命名、启用、停用、删除。自动 Key 使
| 模型及元数据缓存 | `config.json.models.catalog.json`、`config.json.models.dev.json`。 |
| 可用性及轮转 | `config.json.<upstream-fingerprint>.availability.json`、`config.json.rotation.json`。 |
| Session、用量、近期请求/尝试、日志环形缓冲、最近 Playground 结果 | 内存,进程重启清空。 |
| 结构化日志 | stdout JSON,需外部收集才能长期保存。 |
| 结构化日志 | stdout JSON;可用 `logging.file_path` 同步写入磁盘,并保留一份 `.1` 备份。 |
文件名以实际配置路径为前缀。监控保留跨热重载数据,不跨进程共享;Token 只统计上游报告值,不估算缺失用量。完整请求结果与收到响应头为止的尝试指标是不同口径。Playground 用量单独归类。最近一小时最多保留 10,000 请求/20,000 尝试,接口各返回最多 500 条。
@@ -285,6 +285,8 @@ API Key 页面支持创建、命名、启用、停用、删除。自动 Key 使
配置和备份包含上游 Key、代理密码、OAuth Token,密码哈希不加密这些内容。限制文件权限,Windows 使用 ACL,分享源码时排除运行文件。`logging.dump_request_bodies` 默认关闭且需 debug 才输出,即使截断与脱敏仍可能暴露对话内容。Playground 和主动可用性探测会发送真实上游请求,可能消耗额度或 credits。
`logging.file_path` 默认为空(关闭),可在日志设置中热更新。相对路径以配置文件所在目录为基准,保存时不会反复拼接目录。文件接收与 stdout 相同的已脱敏 JSON 记录,在约 32 MiB 的记录边界轮转为 `<路径>.1`,只保留一份备份;单条超大记录可超过阈值。打开或轮转失败不会中断控制台与内存日志,切换目标失败会保留原有 sink。文件在支持的平台使用 `0600` 权限,Windows 仍需单独限制 ACL。请求体转储仍可能包含敏感对话,普通文件追加不保证系统或断电故障下的持久性。
## 本地开发与核对
`cmd/opencode2api` 启动服务;`internal/admin` 负责管理,`gateway` 负责路由/运行时,`protocol` 负责 JSON/SSE 转换,`models` 负责发现,`oauth` 负责官方授权,`config` 负责校验/持久化,`telemetry` 负责监控/日志。静态资源位于 `webui`,无需安装前端依赖。
+7 -2
View File
@@ -51,9 +51,14 @@ func main() {
hub := telemetry.LogHub(cfg.Logging.RingSize)
redactor := config.SecretRedactor()
redactor.Replace(cfg)
logger := telemetry.StructuredLogger(level, hub, redactor)
logFile := telemetry.NewLogFile()
defer logFile.Close()
logger := telemetry.StructuredLogger(level, hub, redactor, logFile)
if err := logFile.Apply(cfg.LogFilePath(*configPath)); err != nil {
logger.Warn("log file path could not be applied; console logging continues", "component", "logging", "event", "log_file_open_failed", "error", err)
}
monitor := telemetry.Monitor()
manager, err := gateway.RuntimeManager(ctx, *configPath, cfg, logger, monitor, hub, redactor, level)
manager, err := gateway.RuntimeManager(ctx, *configPath, cfg, logger, monitor, hub, redactor, level, logFile)
if err != nil {
logger.Error("failed to initialize runtime", "component", "runtime", "event", "runtime_initialization_failed", "error", err)
os.Exit(1)
+1
View File
@@ -47,6 +47,7 @@
"logging": {
"level": "info",
"ring_size": 2000,
"file_path": "",
"dump_request_bodies": false
},
"webui": {
+5
View File
@@ -76,10 +76,15 @@ Common management defaults:
| `webui.listen` | `0.0.0.0:8081`. |
| `logging.level` | `info`; supports `debug`, `info`, `warn`, and `error`. |
| `logging.ring_size` | `2000`; range 100–50,000. |
| `logging.file_path` | Empty disables file logging; relative paths resolve beside the configuration file. Hot-applied. |
| `logging.dump_request_bodies` | `false`; also requires debug logging, capped at 64 KiB per prepared body. |
| `models.active_probes` | `false`; real traffic supplies default availability observations. |
| `keys_direct` | `false`; pins unbound manual Zen/Go keys to dual-stack direct egress; explicit bindings win. Anonymous/OAuth routing is unchanged. |
File logging mirrors the same redacted JSON records sent to stdout. The UI accepts a file path; clearing it disables the sink. Older API clients that omit `logging.file_path` retain the current value, while an explicit empty string disables it. Saving and disk reload apply path changes without restarting. A failed open or retarget reports `log_file_open_failed` and keeps the previous sink; write/rotation failures report `log_file_error` through the independent console/in-memory handler, not recursively through the file sink.
Rotation occurs at record boundaries around 32 MiB, retaining `<path>.1` only; an oversized record is not split. Parent directories are created with mode `0700` and files use `0600` where supported. Configure Windows ACLs separately. File/backup targets cannot overwrite the configuration, its backup, configured proxy file, or known runtime data files. Symlink/non-regular file targets are rejected. Request-body dumps still contain conversation content; treat disk logs as private. Writes are not individually synced, so operating-system/power failure durability is not guaranteed.
## Go OAuth and Zen PAYG OAuth
Models and quota contains two separate panels. Go uses subscription routes; Zen uses Console workspace pay-as-you-go billing (PAYG), and **inference consumes that workspace's credits**. Signing in to Go does not establish Zen permissions or balance, or automatically connect PAYG.
+5
View File
@@ -76,9 +76,14 @@ Key、代理、上游、超时、模型、偏好、reasoning 和日志设置热
| `webui.listen` | `0.0.0.0:8081`。 |
| `logging.level` | `info`;支持 `debug`、`info`、`warn`、`error`。 |
| `logging.ring_size` | `2000`;范围 100–50,000。 |
| `logging.file_path` | 留空关闭落盘;相对路径以配置文件所在目录为基准,支持热更新。 |
| `logging.dump_request_bodies` | `false`;还需 debug 才输出,每个准备好的请求体最多 64 KiB。 |
| `models.active_probes` | `false`;真实流量提供默认可用性观察。 |
日志文件接收与 stdout 相同的已脱敏 JSON 记录。页面可填写路径,清空即关闭;旧 API 客户端省略 `logging.file_path` 时保留当前值,明确传空字符串则关闭。保存与磁盘重载无需重启。打开或切换失败报告 `log_file_open_failed` 并保留原有 sink;写入或轮转失败通过独立的控制台/内存 handler 报告 `log_file_error`,不会递归写入故障文件。
在约 32 MiB 的记录边界轮转,只保留 `<路径>.1`,不会拆开单条超大记录。新目录使用 `0700`、文件使用 `0600`(限平台支持),Windows 需单独配置 ACL。活动文件及备份不能覆盖配置、配置备份、已配置的代理文件与已知运行数据文件;拒绝符号链接和非普通文件目标。请求体转储仍含对话内容,磁盘日志应视为私密数据。每次追加不单独执行同步,不保证系统或断电故障下的持久性。
## Go OAuth 与 Zen PAYG OAuth
「模型与额度」有两个独立面板。Go 使用订阅路由;Zen 使用 Console 工作区按量计费(PAYG),**推理会消耗该工作区 credits**。Go 登录不代表获得 Zen 权限或余额,不会自动连接 PAYG。
+11 -2
View File
@@ -207,6 +207,11 @@ type ModelsUpdate struct {
StripFreeSuffix *bool `json:"strip_free_suffix,omitempty"`
}
type LoggingUpdate struct {
config.LoggingConfig
FilePath *string `json:"file_path,omitempty"`
}
// ConfigUpdate is the body of PUT /api/config. Secrets carry either a new
// value or the ID of the existing one. The WebUI username and password are
// not changed here; they go through /api/account.
@@ -225,7 +230,7 @@ type ConfigUpdate struct {
Retry config.RetryConfig `json:"retry"`
Models ModelsUpdate `json:"models"`
Performance config.PerformanceConfig `json:"performance"`
Logging config.LoggingConfig `json:"logging"`
Logging LoggingUpdate `json:"logging"`
Prefer config.Tier `json:"prefer"`
// A pointer distinguishes an omitted field (legacy clients should keep the
// current reasoning configuration) from an explicit empty object (clear it).
@@ -286,7 +291,7 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile,
ProxyBindings: proxyBindings,
KeysDirect: current.KeysDirect,
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models.ModelsConfig, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer,
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models.ModelsConfig, Performance: update.Performance, Logging: update.Logging.LoggingConfig, Prefer: update.Prefer,
Reasoning: reasoning,
WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes},
}
@@ -310,6 +315,10 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
if update.Models.StripFreeSuffix != nil {
candidate.Models.StripFreeSuffix = *update.Models.StripFreeSuffix
}
candidate.Logging.FilePath = latest.Logging.FilePath
if update.Logging.FilePath != nil {
candidate.Logging.FilePath = *update.Logging.FilePath
}
candidate.WebUI.Username = latest.WebUI.Username
candidate.WebUI.PasswordHash = latest.WebUI.PasswordHash
if update.Reasoning == nil {
+46
View File
@@ -9,6 +9,8 @@ import (
"net/netip"
"net/url"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"unicode"
@@ -250,6 +252,7 @@ func (b *AnonymousBackoffConfig) Normalize() error {
type LoggingConfig struct {
Level string `json:"level"`
RingSize int `json:"ring_size"`
FilePath string `json:"file_path,omitempty"`
// DumpRequestBodies logs the exact bytes sent upstream (redacted, capped)
// so retry and translation problems can be diagnosed without patching the
// binary. Off by default: the bodies contain conversation content.
@@ -486,6 +489,10 @@ func Normalize(path string, cfg Config) (Config, error) {
if cfg.Logging.RingSize < 100 || cfg.Logging.RingSize > 50000 {
return Config{}, errors.New("logging.ring_size must be between 100 and 50000")
}
cfg.Logging.FilePath = strings.TrimSpace(cfg.Logging.FilePath)
if err := cfg.validateLogFilePath(path); err != nil {
return Config{}, err
}
if cfg.WebUI.Password != "" && len(cfg.WebUI.Password) < 10 {
return Config{}, errors.New("webui.password must contain at least 10 characters")
}
@@ -548,6 +555,45 @@ func remapServerKeyMetadata(cfg *Config) {
}
}
func (cfg Config) LogFilePath(configPath string) string {
if cfg.Logging.FilePath == "" || filepath.IsAbs(cfg.Logging.FilePath) {
return cfg.Logging.FilePath
}
return filepath.Join(filepath.Dir(configPath), cfg.Logging.FilePath)
}
func (cfg Config) validateLogFilePath(configPath string) error {
if cfg.Logging.FilePath == "" || configPath == "" {
return nil
}
target, err := filepath.Abs(cfg.LogFilePath(configPath))
if err != nil {
return errors.New("logging.file_path could not be resolved")
}
base, err := filepath.Abs(configPath)
if err != nil {
return errors.New("configuration path could not be resolved")
}
protected := []string{base, base + ".bak", base + ".rotation.json", base + ".models.catalog.json", base + ".models.dev.json"}
fingerprint := Fingerprint(cfg.Upstream.Zen)
protected = append(protected, base+"."+fingerprint+".availability.json", base+"."+fingerprint[:10]+".availability.json")
if cfg.ProxyFile != "" {
proxyPath := cfg.ProxyFile
if !filepath.IsAbs(proxyPath) {
proxyPath = filepath.Join(filepath.Dir(base), proxyPath)
}
protected = append(protected, filepath.Clean(proxyPath))
}
for _, reserved := range protected {
for _, candidate := range []string{target, target + ".1"} {
if candidate == reserved || runtime.GOOS == "windows" && strings.EqualFold(candidate, reserved) {
return errors.New("logging.file_path and its rotation backup must not overwrite configuration or runtime data files")
}
}
}
return nil
}
// normalizeReasoning validates and canonicalizes the forced thinking level.
//
// Levels are stored lowercased so the hot path can compare them without
+8 -2
View File
@@ -62,6 +62,7 @@ type RuntimeController struct {
hub *telemetry.LogBroker
redactor *config.Redactor
level *slog.LevelVar
logFile *telemetry.LogFile
current atomic.Pointer[gatewayRuntime]
updateMu sync.Mutex
oauthMu sync.Mutex
@@ -94,9 +95,9 @@ type EffectiveListeners struct {
// loads the persisted rotation state and the model catalog cache; and starts
// the pricing metadata refresh and the free-model availability checks. It
// fails when the rotation config does not validate against the catalog.
func RuntimeManager(root context.Context, configPath string, cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, hub *telemetry.LogBroker, redactor *config.Redactor, level *slog.LevelVar) (*RuntimeController, error) {
func RuntimeManager(root context.Context, configPath string, cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, hub *telemetry.LogBroker, redactor *config.Redactor, level *slog.LevelVar, logFile *telemetry.LogFile) (*RuntimeController, error) {
manager := &RuntimeController{
configPath: configPath, root: root, logger: logger, monitor: monitor, hub: hub, redactor: redactor, level: level,
configPath: configPath, root: root, logger: logger, monitor: monitor, hub: hub, redactor: redactor, level: level, logFile: logFile,
effective: EffectiveListeners{API: cfg.Listen, WebUI: cfg.WebUI.Listen, WebUIEnabled: cfg.WebUI.Enabled},
}
manager.metadata = modelcatalog.PricingStore(configPath, logger)
@@ -446,6 +447,11 @@ func (m *RuntimeController) applyLocked(candidate config.Config, persist bool) (
result.RestartRequired = len(result.RestartFields) > 0
m.redactor.Replace(normalized)
telemetry.SetLogLevel(m.level, normalized.Logging.Level)
if m.logFile != nil {
if err := m.logFile.Apply(normalized.LogFilePath(m.configPath)); err != nil {
m.logger.Warn("log file path could not be applied; previous sink retained", "component", "logging", "event", "log_file_open_failed", "error", err)
}
}
if current == nil || normalized.Logging.RingSize != current.config.Logging.RingSize {
m.hub.Resize(normalized.Logging.RingSize)
}
+195
View File
@@ -0,0 +1,195 @@
package telemetry
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
)
const logFileLimit = 32 << 20
type LogFile struct {
mu sync.Mutex
file *os.File
path string
size int64
pending error
failed bool
}
func NewLogFile() *LogFile {
return &LogFile{}
}
func (sink *LogFile) Apply(path string) error {
path = strings.TrimSpace(path)
if path == "" {
return sink.Close()
}
resolved, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("resolve log file path: %w", err)
}
sink.mu.Lock()
defer sink.mu.Unlock()
if resolved == sink.path && sink.file != nil {
return nil
}
file, size, err := openLogFile(resolved)
if err != nil {
return err
}
previous := sink.file
sink.file, sink.path, sink.size = file, resolved, size
sink.failed = false
if previous != nil {
if err := previous.Close(); err != nil {
sink.recordErrorLocked(fmt.Errorf("close previous log file: %w", err))
}
}
return nil
}
func (sink *LogFile) Path() string {
sink.mu.Lock()
defer sink.mu.Unlock()
return sink.path
}
func (sink *LogFile) Close() error {
sink.mu.Lock()
defer sink.mu.Unlock()
previous := sink.file
sink.file, sink.path, sink.size = nil, "", 0
sink.failed = false
if previous != nil {
return previous.Close()
}
return nil
}
func (sink *LogFile) TakeError() error {
sink.mu.Lock()
defer sink.mu.Unlock()
err := sink.pending
sink.pending = nil
return err
}
func (sink *LogFile) Write(data []byte) (int, error) {
sink.mu.Lock()
defer sink.mu.Unlock()
if len(data) == 0 || sink.path == "" {
return len(data), nil
}
if sink.file == nil {
file, size, err := openLogFile(sink.path)
if err != nil {
sink.recordErrorLocked(err)
return 0, err
}
sink.file, sink.size = file, size
}
if sink.size > 0 && (sink.size >= logFileLimit || int64(len(data)) > logFileLimit-sink.size) {
if err := sink.rotateLocked(); err != nil {
sink.recordErrorLocked(err)
return 0, err
}
}
written, err := sink.file.Write(data)
sink.size += int64(written)
if err == nil && written != len(data) {
err = io.ErrShortWrite
}
if err != nil {
sink.recordErrorLocked(fmt.Errorf("write log file: %w", err))
} else {
sink.failed = false
}
return written, err
}
func (sink *LogFile) rotateLocked() error {
current, err := os.Lstat(sink.path)
if err != nil {
return fmt.Errorf("inspect active log file: %w", err)
}
opened, err := sink.file.Stat()
if err != nil {
return fmt.Errorf("inspect open log file: %w", err)
}
if !current.Mode().IsRegular() || !os.SameFile(current, opened) {
return errors.New("active log file was replaced or is not a regular file")
}
backup := sink.path + ".1"
if info, err := os.Lstat(backup); err == nil {
if !info.Mode().IsRegular() {
return errors.New("log backup is not a regular file")
}
} else if !os.IsNotExist(err) {
return fmt.Errorf("inspect log backup: %w", err)
}
closeErr := sink.file.Close()
sink.file = nil
var rotateErr error
if closeErr != nil {
rotateErr = fmt.Errorf("close log file for rotation: %w", closeErr)
} else if err := os.Remove(backup); err != nil && !os.IsNotExist(err) {
rotateErr = fmt.Errorf("remove previous log backup: %w", err)
} else if err := os.Rename(sink.path, backup); err != nil {
rotateErr = fmt.Errorf("rotate log file: %w", err)
}
file, size, reopenErr := openLogFile(sink.path)
if reopenErr == nil {
sink.file, sink.size = file, size
}
return errors.Join(rotateErr, reopenErr)
}
func (sink *LogFile) recordErrorLocked(err error) {
if !sink.failed && sink.pending == nil {
sink.pending = err
}
sink.failed = true
}
func openLogFile(path string) (*os.File, int64, error) {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return nil, 0, fmt.Errorf("create log directory: %w", err)
}
if info, err := os.Lstat(path); err == nil {
if !info.Mode().IsRegular() {
return nil, 0, errors.New("log file is not a regular file")
}
} else if !os.IsNotExist(err) {
return nil, 0, fmt.Errorf("inspect log file: %w", err)
}
file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if err != nil {
return nil, 0, fmt.Errorf("open log file: %w", err)
}
opened, err := file.Stat()
if err == nil && !opened.Mode().IsRegular() {
err = errors.New("opened log file is not a regular file")
}
if err == nil {
current, inspectErr := os.Lstat(path)
if inspectErr != nil {
err = inspectErr
} else if !current.Mode().IsRegular() || !os.SameFile(current, opened) {
err = errors.New("log file changed while opening")
}
}
if err == nil {
err = file.Chmod(0o600)
}
if err != nil {
_ = file.Close()
return nil, 0, fmt.Errorf("prepare log file: %w", err)
}
return file, opened.Size(), nil
}
+39 -11
View File
@@ -145,11 +145,13 @@ func (h *LogBroker) Subscribe() (<-chan LogEvent, func()) {
// hubHandler is the slog.Handler behind StructuredLogger. It passes each
// record to base and publishes a redacted copy to hub.
type hubHandler struct {
base slog.Handler
hub *LogBroker
redactor *config.Redactor
attrs []scopedLogAttr
groups []string
base slog.Handler
hub *LogBroker
redactor *config.Redactor
attrs []scopedLogAttr
groups []string
logFile *LogFile
fileErrors *slog.Logger
}
// scopedLogAttr keeps the group active when WithAttrs was called; later
@@ -162,8 +164,31 @@ type scopedLogAttr struct {
// StructuredLogger returns a logger that writes JSON to stdout and mirrors
// every record into hub. Both outputs pass through redactor, and attributes
// whose keys mention a password, authorization, cookie or secret are masked.
func StructuredLogger(level *slog.LevelVar, hub *LogBroker, redactor *config.Redactor) *slog.Logger {
return structuredLogger(os.Stdout, level, hub, redactor)
func StructuredLogger(level *slog.LevelVar, hub *LogBroker, redactor *config.Redactor, file *LogFile) *slog.Logger {
if file == nil {
return structuredLogger(os.Stdout, level, hub, redactor)
}
base := slog.NewJSONHandler(&multiSink{stdout: os.Stdout, file: file}, &slog.HandlerOptions{Level: level})
return slog.New(&hubHandler{
base: base, hub: hub, redactor: redactor, logFile: file,
fileErrors: structuredLogger(os.Stdout, level, hub, redactor),
})
}
type multiSink struct {
stdout io.Writer
file *LogFile
}
func (sink *multiSink) Write(data []byte) (int, error) {
written, err := sink.stdout.Write(data)
if err == nil && written != len(data) {
err = io.ErrShortWrite
}
if sink.file != nil {
_, _ = sink.file.Write(data)
}
return written, err
}
// structuredLogger is StructuredLogger with an explicit JSON output.
@@ -288,9 +313,7 @@ func (h *hubHandler) Handle(ctx context.Context, record slog.Record) error {
h.addAttr(fields, sanitized, h.redactedGroups(h.groups))
return true
})
if err := handler.Handle(ctx, output); err != nil {
return err
}
handleErr := handler.Handle(ctx, output)
component, _ := fields["component"].(string)
delete(fields, "component")
h.hub.Publish(LogEvent{
@@ -300,7 +323,12 @@ func (h *hubHandler) Handle(ctx context.Context, record slog.Record) error {
Component: component,
Fields: fields,
})
return nil
if h.logFile != nil {
if err := h.logFile.TakeError(); err != nil {
h.fileErrors.Warn("log file sink problem", "component", "logging", "event", "log_file_error", "error", err)
}
}
return handleErr
}
func (h *hubHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
+5
View File
@@ -1213,6 +1213,11 @@
<label for="c-ring" data-i18n="config.performance.ring">日志 Ring Size</label>
<input id="c-ring" type="number" />
</div>
<div class="field full">
<label for="c-log-file" data-i18n="config.logging.file">日志文件路径</label>
<input id="c-log-file" autocomplete="off" spellcheck="false" placeholder="logs/gateway.log" />
<p class="section-caption" data-i18n="config.logging.fileHint">留空关闭;相对路径以配置文件所在目录为基准。32 MiB 按记录轮转,保留一份 .1 备份。</p>
</div>
<div class="field full">
<label class="check">
<input id="c-dump-bodies" type="checkbox" />
+6
View File
@@ -369,6 +369,8 @@ const DICTIONARY = {
"config.performance.firstEvent": "First SSE event timeout (seconds, 0 disables)",
"config.performance.level": "Log level",
"config.performance.ring": "Log ring size",
"config.logging.file": "Log file path",
"config.logging.fileHint": "Empty disables file logging; relative paths resolve beside the configuration file. Rotates at record boundaries around 32 MiB, retaining one .1 backup.",
"config.performance.dump":
"Write outbound request dumps (masked, for tracing retries and conversions only)",
"config.reload": "Reload from disk",
@@ -998,6 +1000,8 @@ const DICTIONARY = {
"Timeout sự kiện SSE đầu tiên (giây, 0 để tắt)",
"config.performance.level": "Mức log",
"config.performance.ring": "Kích thước ring log",
"config.logging.file": "Đường dẫn tệp log",
"config.logging.fileHint": "Để trống để tắt; đường dẫn tương đối tính từ thư mục tệp cấu hình. Xoay log theo bản ghi khoảng 32 MiB, giữ một bản sao .1.",
"config.performance.dump":
"Ghi dump request đi ra (đã che, chỉ dùng để truy vết retry và chuyển đổi)",
"config.reload": "Nạp lại từ đĩa",
@@ -1591,6 +1595,8 @@ const DICTIONARY = {
"config.performance.firstEvent": "Timeout del primo evento SSE (secondi, 0 disabilita)",
"config.performance.level": "Livello di log",
"config.performance.ring": "Dimensione ring di log",
"config.logging.file": "Percorso del file di log",
"config.logging.fileHint": "Vuoto disattiva il log su file; i percorsi relativi partono dalla cartella della configurazione. Rotazione tra record intorno a 32 MiB, con una copia .1.",
"config.performance.dump":
"Scrivi i dump delle richieste in uscita (mascherati, solo per tracciare retry e conversioni)",
"config.reload": "Ricarica dal disco",
+2
View File
@@ -122,6 +122,7 @@ function fillConfig(value) {
$("#c-first-event-timeout").value = value.performance.first_event_timeout_seconds || 0;
$("#c-level").value = value.logging.level;
$("#c-ring").value = value.logging.ring_size;
$("#c-log-file").value = value.logging.file_path || "";
$("#c-dump-bodies").checked = !!value.logging.dump_request_bodies;
["server_keys", "zen_keys", "go_keys"].forEach(renderChips);
fillProxies(value.proxies || []);
@@ -197,6 +198,7 @@ async function save(event) {
logging: {
level: $("#c-level").value,
ring_size: numberValue("#c-ring"),
file_path: $("#c-log-file").value.trim(),
dump_request_bodies: $("#c-dump-bodies").checked,
},
webui: {