updated hlog

This commit is contained in:
2026-01-13 12:55:30 +11:00
parent 8c2ca4d79a
commit 2a8c39002d
12 changed files with 1224 additions and 21 deletions

View File

@@ -7,17 +7,45 @@ import (
"github.com/pkg/errors"
)
// Returns a pointer to a new log file with the specified path.
// Remember to call file.Close() when finished writing to the log file
func NewLogFile(path string) (*os.File, error) {
logPath := filepath.Join(path, "server.log")
file, err := os.OpenFile(
logPath,
os.O_APPEND|os.O_CREATE|os.O_WRONLY,
0663,
)
// newLogFile creates or opens the log file based on the configuration.
// The file is created in the specified directory with the configured filename.
// File permissions are set to 0663 (rw-rw--w-).
//
// If append is true, the file is opened in append mode and new logs are added
// to the end. If append is false, the file is truncated on open, overwriting
// any existing content.
//
// Returns an error if the file cannot be opened or created.
func newLogFile(dir, filename string, append bool) (*os.File, error) {
logPath := filepath.Join(dir, filename)
flags := os.O_CREATE | os.O_WRONLY
if append {
flags |= os.O_APPEND
} else {
flags |= os.O_TRUNC
}
file, err := os.OpenFile(logPath, flags, 0663)
if err != nil {
return nil, errors.Wrap(err, "os.OpenFile")
}
return file, nil
}
// CloseLogFile closes the underlying log file if one is open.
// This should be called when shutting down the application to ensure
// all buffered logs are flushed to disk.
//
// If no log file is open, this is a no-op and returns nil.
// Returns an error if the file cannot be closed.
func (l *Logger) CloseLogFile() error {
if l.logFile == nil {
return nil
}
err := l.logFile.Close()
if err != nil {
return err
}
return nil
}