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

111 lines
1.9 KiB
Go
Raw Permalink Normal View History

2022-03-08 01:17:24 +04:00
package logging
import (
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/pkg/errors"
)
type Logger struct {
file io.WriteCloser
toStdout bool
mut sync.Mutex
}
// 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)
if err != nil {
return nil, errors.Wrap(err, "failed to open log file")
}
return &Logger{file: f, toStdout: toStdout}, nil
}
2022-05-24 23:33:37 +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-03-08 01:17:24 +04:00
func (l *Logger) Println(v ...interface{}) {
l.mut.Lock()
defer l.mut.Unlock()
nowStr := time.Now().UTC().Format(time.RFC3339)
fmt.Fprintln(l.file, nowStr, v)
if l.toStdout {
fmt.Println(v...)
2022-03-08 01:17:24 +04:00
}
}
func (l *Logger) Printf(format string, v ...interface{}) {
l.mut.Lock()
defer l.mut.Unlock()
// 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...)
if l.toStdout {
fmt.Printf(format, v...)
2022-03-08 01:17:24 +04:00
}
}
func (l *Logger) Fatalln(v ...interface{}) {
l.mut.Lock()
nowStr := time.Now().UTC().Format(time.RFC3339)
fmt.Fprintln(l.file, nowStr, v)
if l.toStdout {
fmt.Println(v...)
2022-03-08 01:17:24 +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...)
if l.toStdout {
fmt.Printf(format, v...)
2022-03-08 01:17:24 +04:00
}
l.file.Close()
os.Exit(1)
}
func (l *Logger) Close() error {
return l.file.Close()
}