-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
102 lines (85 loc) · 2.33 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package log
import (
"io"
"os"
"path/filepath"
"runtime"
"github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
)
type Options struct {
// FileName string // 日志文件名,不包含路径
MaxSizeInMB int // 日志文件大小,单位MB,>=1
MaxBackups int // 日志文件最大备份数,>=1
Formatter logrus.Formatter
DisableStderr bool // 设置后不再打印到标准错误
EnableMemory bool // 日志文件保存在内存中,降低硬盘IO
}
const MEMORY_LOGS_DIR = "/dev/shm/logs"
func New(filename string, option ...*Options) *logrus.Logger {
if filename == "" {
filename = "./unknown.log"
}
basename := filepath.Base(filename)
options := &Options{}
if len(option) > 0 {
options = option[0]
}
// options
maxsize := 20
if options.MaxSizeInMB > 1 {
maxsize = options.MaxSizeInMB
}
maxbackups := 1
if options.MaxBackups > 1 {
maxbackups = options.MaxBackups
}
var formatter logrus.Formatter = &myFormatter{}
if options.Formatter != nil {
formatter = options.Formatter
}
var realfilename string
if runtime.GOOS == "linux" && options.EnableMemory {
os.MkdirAll(MEMORY_LOGS_DIR, 0755)
realfilename = filepath.Join(MEMORY_LOGS_DIR, basename)
} else {
// filenamepath = filepath.Join("./", filename)
realfilename = filename
}
// lumberjack logger作为logrus的输出
output := &lumberjack.Logger{
Filename: realfilename, // in memory
MaxSize: maxsize, // megabytes
MaxBackups: maxbackups, // reserve 1 backup
// MaxAge: 28, //days
Compress: true,
LocalTime: true,
}
logger := &logrus.Logger{
Out: output,
// Formatter: &logrus.TextFormatter{},
Formatter: formatter,
Hooks: make(logrus.LevelHooks),
Level: logrus.DebugLevel,
}
logger.SetReportCaller(true)
// 设置后不再打印到标准错误
if !options.DisableStderr {
AppendOutput(logger, os.Stderr)
}
// 在当前目录创建链接
if runtime.GOOS == "linux" && options.EnableMemory {
dir := filepath.Dir(filename)
os.MkdirAll(dir, 0755)
os.Symlink(realfilename, filename)
}
return logger
}
// SetLogLevel 设置日志级别
func SetLevel(logger *logrus.Logger, level logrus.Level) {
logger.SetLevel(level)
}
// AppendOutput 添加日志输出
func AppendOutput(logger *logrus.Logger, output io.Writer) {
logger.SetOutput(io.MultiWriter(logger.Out, output))
}