-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
74 lines (59 loc) · 1.79 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
package log
import (
"fmt"
"log"
"net/http"
"runtime"
)
const defaultSkippedCallers = 4
// We need to increase because this logger is called from exported functions
// and we don't want to see these functions in the log statement, we want
// the function name above in the call stack.
var defaultLogger = NewLogger().IncreaseSkippedCallers()
func Info(req *http.Request, format string, v ...interface{}) {
defaultLogger.Info(req, format, v...)
}
func Warn(req *http.Request, format string, v ...interface{}) {
defaultLogger.Warn(req, format, v...)
}
func Error(req *http.Request, err error) error {
return defaultLogger.Error(req, err)
}
type Logger struct {
skipCallers int
}
func NewLogger() *Logger {
return &Logger{defaultSkippedCallers}
}
func (logger *Logger) IncreaseSkippedCallers() *Logger {
return &Logger{logger.skipCallers + 1}
}
func (logger *Logger) DecreaseSkippedCallers() *Logger {
return &Logger{logger.skipCallers - 1}
}
func (logger *Logger) Info(req *http.Request, format string, v ...interface{}) {
logger.printRecord("INFO", req, format, v...)
}
func (logger *Logger) Warn(req *http.Request, format string, v ...interface{}) {
logger.printRecord("WARNING", req, format, v...)
}
func (logger *Logger) Error(req *http.Request, err error) error {
logger.printRecord("ERROR", req, err.Error())
return err
}
func (logger *Logger) printRecord(
kind string,
req *http.Request,
format string,
v ...interface{},
) {
log.Printf("%v [request = %v %v] [position = %v]: %v\n",
kind, req.Method, req.URL.Path, logger.trace(), fmt.Sprintf(format, v...))
}
func (logger *Logger) trace() string {
pc := make([]uintptr, 1)
runtime.Callers(logger.skipCallers, pc)
fn := runtime.FuncForPC(pc[0])
file, line := fn.FileLine(pc[0])
return fmt.Sprintf("%s:%d %s", file, line, fn.Name())
}