forked from zhaojh329/rttys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
71 lines (56 loc) · 1.39 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
64
65
66
67
68
69
70
71
package log
import (
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/dwdcth/consoleEx"
"github.com/mattn/go-colorable"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"golang.org/x/crypto/ssh/terminal"
)
type logFileHook struct {
err error
path string
}
var logFile = &logFileHook{}
func (h *logFileHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
if h.err != nil {
return
}
f, err := os.OpenFile(h.path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
h.err = err
log.Fatal().Msg(err.Error())
return
}
defer f.Close()
f.WriteString(zerolog.TimestampFunc().Format(zerolog.TimeFieldFormat) + " |")
f.WriteString(strings.ToUpper(level.String()) + "| ")
_, file, line, ok := runtime.Caller(3)
if ok {
f.WriteString(zerolog.CallerMarshalFunc(file, line) + " |")
}
f.WriteString(msg)
f.WriteString("\n")
}
func init() {
zerolog.CallerMarshalFunc = func(file string, line int) string {
return filepath.Base(file) + ":" + strconv.Itoa(line)
}
out := consoleEx.ConsoleWriterEx{Out: colorable.NewColorableStdout()}
logger := zerolog.New(out).With().Timestamp().Logger()
if !terminal.IsTerminal(int(os.Stdout.Fd())) {
logger = logger.Hook(logFile)
}
log.Logger = logger
}
// SetPath set the log file path
func SetPath(path string) {
logFile.path = path
}
func Verbose() {
log.Logger = log.Logger.With().Caller().Logger()
}