From f92267a2883c38940c1d7b6c1ed020b70dae0762 Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Mon, 7 Feb 2022 21:24:54 +0400 Subject: [PATCH] Added optional writing to stdout. --- pkg/logging/logger.go | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/pkg/logging/logger.go b/pkg/logging/logger.go index 96bd88b..c6683c4 100644 --- a/pkg/logging/logger.go +++ b/pkg/logging/logger.go @@ -12,17 +12,20 @@ import ( ) type Logger struct { - file io.WriteCloser - mut sync.Mutex + 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) }