-
Notifications
You must be signed in to change notification settings - Fork 3
/
logging.go
395 lines (343 loc) · 8.75 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// SiYuan - Build Your Eternal Digital Garden
// Copyright (c) 2020-present, b3log.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package logging
import (
"bytes"
"fmt"
"io"
stdlog "log"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"strings"
"sync"
"github.com/88250/gulu"
)
const (
ExitCodeReadOnlyDatabase = 20 // 数据库文件被锁
ExitCodeUnavailablePort = 21 // 端口不可用
ExitCodeWorkspaceLocked = 24 // 工作空间已被锁定
ExitCodeInitWorkspaceErr = 25 // 初始化工作空间失败
ExitCodeFileSysErr = 26 // 文件系统错误
ExitCodeOk = 0 // 正常退出
ExitCodeFatal = 1 // 致命错误
)
func ShortStack() string {
output := string(debug.Stack())
lines := strings.Split(output, "\n")
if 5 < len(lines) {
lines = lines[5:]
}
buf := bytes.Buffer{}
for _, l := range lines {
if strings.Contains(l, "gin-gonic") {
break
}
buf.WriteString(" ")
buf.WriteString(l)
buf.WriteByte('\n')
}
return buf.String()
}
var (
logger *Logger
logFile *os.File
LogPath string
)
func init() {
dir, err := os.Getwd()
if nil != err {
stdlog.Printf("get current dir failed: %s", err)
dir = "./"
}
LogPath = filepath.Join(dir, "logging.log")
}
func SetLogPath(path string) {
LogPath = path
}
func LogTracef(format string, v ...interface{}) {
defer closeLogger()
openLogger()
if !logger.IsTraceEnabled() {
return
}
logger.Tracef(format, v...)
}
func LogDebugf(format string, v ...interface{}) {
defer closeLogger()
openLogger()
if !logger.IsDebugEnabled() {
return
}
logger.Debugf(format, v...)
}
func LogInfof(format string, v ...interface{}) {
defer closeLogger()
openLogger()
logger.Infof(format, v...)
}
func LogErrorf(format string, v ...interface{}) {
defer closeLogger()
openLogger()
logger.Errorf(format, v...)
}
func LogWarnf(format string, v ...interface{}) {
defer closeLogger()
openLogger()
if !logger.IsWarnEnabled() {
return
}
logger.Warnf(format, v...)
}
func LogFatalf(exitCode int, format string, v ...interface{}) {
openLogger()
logger.Fatalf(exitCode, format, v...)
}
var lock = sync.Mutex{}
func openLogger() {
lock.Lock()
if gulu.File.IsExist(LogPath) {
if size := gulu.File.GetFileSize(LogPath); 1024*1024*32 <= size {
// 日志文件大于 32M 的话删了重建
os.Remove(LogPath)
}
}
dir, _ := filepath.Split(LogPath)
if !gulu.File.IsExist(dir) {
if err := os.MkdirAll(dir, 0755); nil != err {
stdlog.Printf("create log dir [%s] failed: %s", dir, err)
}
}
var err error
logFile, err = os.OpenFile(LogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if nil != err {
stdlog.Printf("create log file [%s] failed: %s", LogPath, err)
}
logger = NewLogger(io.MultiWriter(os.Stdout, logFile))
}
func closeLogger() {
logFile.Close()
lock.Unlock()
}
func Recover() {
if e := recover(); nil != e {
stack := stack()
msg := fmt.Sprintf("PANIC RECOVERED: %v\n\t%s\n", e, stack)
LogErrorf(msg)
}
}
var (
dunno = []byte("???")
centerDot = []byte("·")
dot = []byte(".")
slash = []byte("/")
)
// stack implements Stack, skipping 2 frames.
func stack() []byte {
buf := &bytes.Buffer{} // the returned data
// As we loop, we open files and read them. These variables record the currently
// loaded file.
var lines [][]byte
var lastFile string
for i := 2; ; i++ { // Caller we care about is the user, 2 frames up
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
// Print this much at least. If we can't find the source, it won't show.
fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
if file != lastFile {
data, err := os.ReadFile(file)
if err != nil {
continue
}
lines = bytes.Split(data, []byte{'\n'})
lastFile = file
}
line-- // in stack trace, lines are 1-indexed but our array is 0-indexed
fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
}
return buf.Bytes()
}
// source returns a space-trimmed slice of the n'th line.
func source(lines [][]byte, n int) []byte {
if n < 0 || n >= len(lines) {
return dunno
}
return bytes.Trim(lines[n], " \t")
}
// function returns, if possible, the name of the function containing the PC.
func function(pc uintptr) []byte {
fn := runtime.FuncForPC(pc)
if fn == nil {
return dunno
}
name := []byte(fn.Name())
// The name includes the path name to the package, which is unnecessary
// since the file name is already included. Plus, it has center dots.
// That is, we see
// runtime/debug.*T·ptrmethod
// and want
// *T.ptrmethod
// Since the package path might contains dots (e.g. code.google.com/...),
// we first remove the path prefix if there is one.
if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {
name = name[lastslash+1:]
}
if period := bytes.Index(name, dot); period >= 0 {
name = name[period+1:]
}
name = bytes.Replace(name, centerDot, dot, -1)
return name
}
// Logging level.
const (
Off = iota
Trace
Debug
Info
Warn
Error
Fatal
)
// the global default logging level, it will be used for creating logger.
var logLevel = Debug
// Logger represents a simple logger with level.
// The underlying logger is the standard Go logging "log".
type Logger struct {
level int
logger *stdlog.Logger
}
// NewLogger creates a logger.
func NewLogger(out io.Writer) *Logger {
ret := &Logger{level: logLevel, logger: stdlog.New(out, "", stdlog.Ldate|stdlog.Ltime|stdlog.Lshortfile)}
return ret
}
// SetLogLevel sets the logging level of all loggers.
func SetLogLevel(level string) {
logLevel = getLevel(level)
}
// getLevel gets logging level int value corresponding to the specified level.
func getLevel(level string) int {
level = strings.ToLower(level)
switch level {
case "off":
return Off
case "trace":
return Trace
case "debug":
return Debug
case "info":
return Info
case "warn":
return Warn
case "error":
return Error
case "fatal":
return Fatal
default:
return Info
}
}
// SetLevel sets the logging level of a logger.
func (l *Logger) SetLevel(level string) {
l.level = getLevel(level)
}
// IsTraceEnabled determines whether the trace level is enabled.
func (l *Logger) IsTraceEnabled() bool {
return l.level <= Trace
}
// IsDebugEnabled determines whether the debug level is enabled.
func (l *Logger) IsDebugEnabled() bool {
return l.level <= Debug
}
// IsWarnEnabled determines whether the debug level is enabled.
func (l *Logger) IsWarnEnabled() bool {
return l.level <= Warn
}
// Tracef prints trace level message with format.
func (l *Logger) Tracef(format string, v ...interface{}) {
if Trace < l.level {
return
}
l.logger.SetPrefix("T ")
l.logger.Output(3, fmt.Sprintf(format, v...))
}
// Debugf prints debug level message with format.
func (l *Logger) Debugf(format string, v ...interface{}) {
if Debug < l.level {
return
}
l.logger.SetPrefix("D ")
l.logger.Output(3, fmt.Sprintf(format, v...))
}
// Infof prints info level message with format.
func (l *Logger) Infof(format string, v ...interface{}) {
if Info < l.level {
return
}
l.logger.SetPrefix("I ")
l.logger.Output(3, fmt.Sprintf(format, v...))
}
// Warnf prints warning level message with format.
func (l *Logger) Warnf(format string, v ...interface{}) {
if Warn < l.level {
return
}
l.logger.SetPrefix("W ")
msg := fmt.Sprintf(format, v...)
l.logger.Output(3, msg)
}
// Errorf prints error level message with format.
func (l *Logger) Errorf(format string, v ...interface{}) {
if Error < l.level {
return
}
l.logger.SetPrefix("E ")
msg := fmt.Sprintf(format, v...)
l.logger.Output(3, msg)
}
// Fatalf prints fatal level message with format and exit process with code 1.
func (l *Logger) Fatalf(exitCode int, format string, v ...interface{}) {
if Fatal < l.level {
return
}
l.logger.SetPrefix("F ")
format += "\n%s"
v = append(v, shortStack())
msg := fmt.Sprintf(format, v...)
l.logger.Output(3, msg)
closeLogger()
os.Exit(exitCode)
}
func shortStack() string {
output := string(debug.Stack())
lines := strings.Split(output, "\n")
if 11 < len(lines) {
lines = lines[11:]
}
buf := bytes.Buffer{}
for _, l := range lines {
if strings.Contains(l, "gin-gonic") {
break
}
buf.WriteString(" ")
buf.WriteString(l)
buf.WriteByte('\n')
}
return buf.String()
}