52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
package hlog
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
// 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
|
|
}
|