1
0

Wrote a simple logger.

This commit is contained in:
Alexander Andreev 2022-02-07 19:35:25 +04:00
parent 64ab7e5d40
commit bde46d93b0
Signed by: Arav
GPG Key ID: 1327FE8A374CC86F

82
pkg/logging/logger.go Normal file
View File

@ -0,0 +1,82 @@
package logging
import (
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/pkg/errors"
)
type Logger struct {
file io.WriteCloser
mut sync.Mutex
}
func NewLogger(path string) (*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
}
func (l *Logger) Println(v ...interface{}) {
l.mut.Lock()
nowStr := time.Now().UTC().Format(time.RFC3339)
fmt.Fprintln(l.file, nowStr, v)
l.mut.Unlock()
}
func (l *Logger) Printf(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...)
l.mut.Unlock()
}
func (l *Logger) Fatalln(v ...interface{}) {
l.mut.Lock()
nowStr := time.Now().UTC().Format(time.RFC3339)
fmt.Fprintln(l.file, nowStr, v)
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...)
l.file.Close()
os.Exit(1)
}
func (l *Logger) Close() error {
return l.file.Close()
}