-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlogger.go
65 lines (56 loc) · 1.15 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Released under MIT License
// Copyright (c) 2022 domosekai
// Custom logger with mutex
package main
import (
"log"
"os"
"sync"
)
type Logger struct {
logger *log.Logger
file *os.File
rw sync.RWMutex
}
func (l *Logger) Open(filename string, append bool) {
l.rw.Lock()
defer l.rw.Unlock()
// Close current file first
if l.file != nil {
l.file.Close()
}
if filename != "" {
var err error
if append {
l.file, err = os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
} else {
l.file, err = os.Create(filename)
}
if err != nil {
log.Fatalf("Failed to create log file. Error: %s", err)
}
l.logger = log.New(l.file, "", log.Ldate|log.Ltime|log.Lmicroseconds)
} else {
l.logger = log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lmicroseconds)
}
}
func (l *Logger) Close() {
if l.file != nil {
l.file.Close()
}
}
func (l *Logger) Printf(format string, v ...any) {
l.rw.RLock()
l.logger.Printf(format, v...)
l.rw.RUnlock()
}
func (l *Logger) Print(v ...any) {
l.rw.RLock()
l.logger.Print(v...)
l.rw.RUnlock()
}
func (l *Logger) Println(v ...any) {
l.rw.RLock()
l.logger.Println(v...)
l.rw.RUnlock()
}