1
0

Added optional writing to stdout.

This commit is contained in:
Alexander Andreev 2022-02-07 21:24:54 +04:00
parent 17152581a9
commit f92267a288
Signed by: Arav
GPG Key ID: 1327FE8A374CC86F

View File

@ -13,16 +13,19 @@ import (
type Logger struct { type Logger struct {
file io.WriteCloser file io.WriteCloser
toStdout bool
mut sync.Mutex mut sync.Mutex
} }
func NewLogger(path string) (*Logger, error) { // NewLogger creates a Logger instance with given filename and
// toStdout tells wether to write to Stdout as well or not.
func NewLogger(path string, toStdout bool) (*Logger, error) {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModeAppend) f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModeAppend)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to open log file") return nil, errors.Wrap(err, "failed to open log file")
} }
return &Logger{file: f}, nil return &Logger{file: f, toStdout: toStdout}, nil
} }
func (l *Logger) Println(v ...interface{}) { func (l *Logger) Println(v ...interface{}) {
@ -32,6 +35,10 @@ func (l *Logger) Println(v ...interface{}) {
fmt.Fprintln(l.file, nowStr, v) fmt.Fprintln(l.file, nowStr, v)
if l.toStdout {
fmt.Println(nowStr, v)
}
l.mut.Unlock() l.mut.Unlock()
} }
@ -47,6 +54,10 @@ func (l *Logger) Printf(format string, v ...interface{}) {
fmt.Fprintf(l.file, nowStr+" "+format, v...) fmt.Fprintf(l.file, nowStr+" "+format, v...)
if l.toStdout {
fmt.Printf(nowStr+" "+format, v...)
}
l.mut.Unlock() l.mut.Unlock()
} }
@ -57,6 +68,10 @@ func (l *Logger) Fatalln(v ...interface{}) {
fmt.Fprintln(l.file, nowStr, v) fmt.Fprintln(l.file, nowStr, v)
if l.toStdout {
fmt.Println(nowStr, v)
}
l.file.Close() l.file.Close()
os.Exit(1) os.Exit(1)
} }
@ -73,6 +88,10 @@ func (l *Logger) Fatalf(format string, v ...interface{}) {
fmt.Fprintf(l.file, nowStr+" "+format, v...) fmt.Fprintf(l.file, nowStr+" "+format, v...)
if l.toStdout {
fmt.Printf(nowStr+" "+format, v...)
}
l.file.Close() l.file.Close()
os.Exit(1) os.Exit(1)
} }