feat: add portable directory safeguards

This commit is contained in:
QiuSW
2026-07-28 00:12:29 +08:00
parent 92091a6690
commit 733954ddc8
15 changed files with 914 additions and 95 deletions
+16
View File
@@ -3,6 +3,8 @@ package logging
import (
"io"
"log/slog"
"os"
"path/filepath"
)
// New creates the process logger. Callers provide the sink so tests and the
@@ -13,3 +15,17 @@ func New(w io.Writer) *slog.Logger {
}
return slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{Level: slog.LevelInfo}))
}
// OpenFile creates an append-only local diagnostic log in the configured
// directory. It never falls back to cwd, so a bad configured directory stays
// visible to the caller instead of scattering logs beside a shortcut.
func OpenFile(directory string) (*slog.Logger, io.Closer, error) {
if err := os.MkdirAll(directory, 0o700); err != nil {
return nil, nil, err
}
file, err := os.OpenFile(filepath.Join(directory, "chub.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
return nil, nil, err
}
return New(file), file, nil
}