-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlog.go
63 lines (51 loc) · 1.02 KB
/
log.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
package main
import (
"fmt"
"io"
"log"
"os"
"sync"
)
var logger = log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Lshortfile)
func Verbose(v ...any) {
if Cfg.Verbose {
_ = logger.Output(3, fmt.Sprint(v...))
}
}
// Error Log
func Error(v ...any) {
_ = logger.Output(3, "ERROR: "+fmt.Sprint(v...))
}
// --------------------------------
// File Output
// --------------------------------
var (
logFile *os.File
logFileMu sync.Mutex
)
func SetLoggerFile(filename string) error {
logFileMu.Lock()
defer logFileMu.Unlock()
oldFile := logFile
f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
return fmt.Errorf("error opening file: %w", err)
}
logFile = f
logger.SetOutput(io.MultiWriter(f, os.Stderr))
if oldFile != nil {
return oldFile.Close()
}
return nil
}
func CloseLoggerFile(w io.Writer) error {
logFileMu.Lock()
defer logFileMu.Unlock()
if logFile == nil {
return nil
}
logger.SetOutput(w)
oldLogFile := logFile
logFile = nil
return oldLogFile.Close()
}