1
0
dwelling-upload/pkg/logging/logger.go

111 lines
1.9 KiB
Go
Raw Normal View History

2022-02-07 19:35:25 +04:00
package logging
import (
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/pkg/errors"
)
type Logger struct {
2022-02-07 21:24:54 +04:00
file io.WriteCloser
toStdout bool
mut sync.Mutex
2022-02-07 19:35:25 +04:00
}
2022-02-07 21:24:54 +04:00
// 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, 0660)
2022-02-07 19:35:25 +04:00
if err != nil {
return nil, errors.Wrap(err, "failed to open log file")
}
2022-02-07 21:24:54 +04:00
return &Logger{file: f, toStdout: toStdout}, nil
2022-02-07 19:35:25 +04:00
}
2022-05-25 00:33:11 +04:00
func (l *Logger) Reopen(path string) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
if err != nil {
return err
}
l.file.Close()
l.file = f
return nil
}
2022-02-07 19:35:25 +04:00
func (l *Logger) Println(v ...interface{}) {
l.mut.Lock()
defer l.mut.Unlock()
2022-02-07 19:35:25 +04:00
nowStr := time.Now().UTC().Format(time.RFC3339)
fmt.Fprintln(l.file, nowStr, v)
2022-02-07 21:24:54 +04:00
if l.toStdout {
2022-03-29 18:15:06 +04:00
fmt.Println(v...)
2022-02-07 21:24:54 +04:00
}
2022-02-07 19:35:25 +04:00
}
func (l *Logger) Printf(format string, v ...interface{}) {
l.mut.Lock()
defer l.mut.Unlock()
2022-02-07 19:35:25 +04:00
// Ensure a new line will be written
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
nowStr := time.Now().UTC().Format(time.RFC3339)
fmt.Fprintf(l.file, nowStr+" "+format, v...)
2022-02-07 19:35:25 +04:00
2022-02-07 21:24:54 +04:00
if l.toStdout {
2022-03-29 18:12:57 +04:00
fmt.Printf(format, v...)
2022-02-07 21:24:54 +04:00
}
2022-02-07 19:35:25 +04:00
}
func (l *Logger) Fatalln(v ...interface{}) {
l.mut.Lock()
nowStr := time.Now().UTC().Format(time.RFC3339)
fmt.Fprintln(l.file, nowStr, v)
2022-02-07 21:24:54 +04:00
if l.toStdout {
2022-03-29 18:15:06 +04:00
fmt.Println(v...)
2022-02-07 21:24:54 +04:00
}
2022-02-07 19:35:25 +04:00
l.file.Close()
os.Exit(1)
}
func (l *Logger) Fatalf(format string, v ...interface{}) {
l.mut.Lock()
// Ensure a new line will be written
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
nowStr := time.Now().UTC().Format(time.RFC3339)
fmt.Fprintf(l.file, nowStr+" "+format, v...)
2022-02-07 19:35:25 +04:00
2022-02-07 21:24:54 +04:00
if l.toStdout {
2022-03-29 18:12:57 +04:00
fmt.Printf(format, v...)
2022-02-07 21:24:54 +04:00
}
2022-02-07 19:35:25 +04:00
l.file.Close()
os.Exit(1)
}
func (l *Logger) Close() error {
return l.file.Close()
}