Added optional writing to stdout.
This commit is contained in:
parent
17152581a9
commit
f92267a288
@ -13,16 +13,19 @@ import (
|
||||
|
||||
type Logger struct {
|
||||
file io.WriteCloser
|
||||
toStdout bool
|
||||
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)
|
||||
if err != nil {
|
||||
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{}) {
|
||||
@ -32,6 +35,10 @@ func (l *Logger) Println(v ...interface{}) {
|
||||
|
||||
fmt.Fprintln(l.file, nowStr, v)
|
||||
|
||||
if l.toStdout {
|
||||
fmt.Println(nowStr, v)
|
||||
}
|
||||
|
||||
l.mut.Unlock()
|
||||
}
|
||||
|
||||
@ -47,6 +54,10 @@ func (l *Logger) Printf(format string, v ...interface{}) {
|
||||
|
||||
fmt.Fprintf(l.file, nowStr+" "+format, v...)
|
||||
|
||||
if l.toStdout {
|
||||
fmt.Printf(nowStr+" "+format, v...)
|
||||
}
|
||||
|
||||
l.mut.Unlock()
|
||||
}
|
||||
|
||||
@ -57,6 +68,10 @@ func (l *Logger) Fatalln(v ...interface{}) {
|
||||
|
||||
fmt.Fprintln(l.file, nowStr, v)
|
||||
|
||||
if l.toStdout {
|
||||
fmt.Println(nowStr, v)
|
||||
}
|
||||
|
||||
l.file.Close()
|
||||
os.Exit(1)
|
||||
}
|
||||
@ -73,6 +88,10 @@ func (l *Logger) Fatalf(format string, v ...interface{}) {
|
||||
|
||||
fmt.Fprintf(l.file, nowStr+" "+format, v...)
|
||||
|
||||
if l.toStdout {
|
||||
fmt.Printf(nowStr+" "+format, v...)
|
||||
}
|
||||
|
||||
l.file.Close()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user