usage: Append makes the log's folder only when it is missing (#3725)
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) at1360689ef, 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 at1360689efplus 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.
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user