From e1709ab42e17ba6f98debca58b84475396990fc5 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 27 Oct 2026 01:58:09 +0800 Subject: [PATCH] usage: Append makes the log's folder only when it is missing (#3725) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every request appends one line to usage.jsonl, and Append ran os.MkdirAll on the folder first each time: a stat, and on its error path a walk up the tree. Now the file is opened first, and the folder is made (then the open tried again) only when that open says it doesn't exist. Measured with a scratch benchmark (not committed) at 1360689ef, Append into an existing folder, -count 5: 3070 B and 25 allocs per call before, 2445 B and 20 allocs after. Wall time is the write itself, ~45-60µs, and at machine load ~160 the run-to-run noise was bigger than the saved stat, so no time saving is claimed. A scratch test with XDG_CONFIG_HOME under two missing folders checked the first Append still creates them and the file. Run at 1360689ef plus this change: gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage ok; go test -count=1 -timeout 45m ./internal/usage ok. --- internal/usage/usage.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/internal/usage/usage.go b/internal/usage/usage.go index b6eebf19e..608c8d8ba 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -7,7 +7,9 @@ package usage import ( "bufio" "encoding/json" + "errors" "fmt" + "io/fs" "math" "os" "path/filepath" @@ -243,10 +245,12 @@ func Append(r Record) { } mu.Lock() defer mu.Unlock() - if err := os.MkdirAll(filepath.Dir(Path()), 0o755); err != nil { - return - } + // the folder is made only when it is missing: every request appends, + // and MkdirAll stat'ed it each time (#3725) f, err := os.OpenFile(Path(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) + if errors.Is(err, fs.ErrNotExist) && os.MkdirAll(filepath.Dir(Path()), 0o755) == nil { + f, err = os.OpenFile(Path(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) + } if err != nil { return }