-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging.go
49 lines (40 loc) · 1.01 KB
/
logging.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
package main
import (
"fmt"
"github.com/fatih/color"
"github.com/sirupsen/logrus"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
var logger *logrus.Logger
var onceLogger sync.Once
func initLogger() {
onceLogger.Do(func() {
logger = logrus.New()
logger.SetReportCaller(true)
logger.SetFormatter(new(MyFormatter))
logger.SetOutput(os.Stdout)
logger.SetLevel(logrus.DebugLevel)
})
}
type MyFormatter struct{}
func (f *MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
timestamp := time.Now().Format("2006-01-02 15:04:05")
file := ""
if entry.HasCaller() {
file = fmt.Sprintf("%s:%d", filepath.Base(entry.Caller.File), entry.Caller.Line)
}
msg := fmt.Sprintf("%s %s (%s) %s\n", strings.ToUpper(entry.Level.String()), timestamp, file, entry.Message)
switch entry.Level {
case logrus.WarnLevel:
msg = color.YellowString(msg)
case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
msg = color.RedString(msg)
default:
msg = color.BlueString(msg)
}
return []byte(msg), nil
}