-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathdefault_logger.go
More file actions
171 lines (144 loc) · 4.64 KB
/
Copy pathdefault_logger.go
File metadata and controls
171 lines (144 loc) · 4.64 KB
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
package logger
import (
"fmt"
"io"
"os"
"strconv"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/internal/logtemplate"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"github.com/valyala/bytebufferpool"
)
// default logger for fiber
func defaultLoggerInstance(c fiber.Ctx, data *Data, cfg *Config) error {
if cfg == nil {
cfg = &Config{
Stream: os.Stdout,
Format: DefaultFormat,
enableColors: true,
}
}
// Check if Skip is defined and call it.
// Now, if Skip(c) == true, we SKIP logging:
if cfg.Skip != nil && cfg.Skip(c) {
return nil // Skip logging if Skip returns true
}
// Alias colors
colors := c.App().Config().ColorScheme
// Get new buffer
buf := bytebufferpool.Get()
// Default output when no custom Format or io.Writer is given
if cfg.Format == DefaultFormat {
// Format error if exist
formatErr := ""
if cfg.enableColors {
if data.ChainErr != nil {
formatErr = colors.Red + " | " + data.ChainErr.Error() + colors.Reset
}
fmt.Fprintf(
buf,
"%s |%s %3d %s| %13v | %15s |%s %-7s %s| %-"+data.ErrPaddingStr+"s %s\n",
data.Timestamp.Load().(string), //nolint:forcetypeassert,errcheck // Timestamp is always a string
statusColor(c.Response().StatusCode(), &colors), c.Response().StatusCode(), colors.Reset,
data.Stop.Sub(data.Start),
c.IP(),
methodColor(c.Method(), &colors), c.Method(), colors.Reset,
c.Path(),
formatErr,
)
} else {
if data.ChainErr != nil {
formatErr = " | " + data.ChainErr.Error()
}
// Helper function to append fixed-width string with padding
fixedWidth := func(s string, width int, rightAlign bool) {
if rightAlign {
for i := len(s); i < width; i++ {
buf.WriteByte(' ')
}
buf.WriteString(s)
} else {
buf.WriteString(s)
for i := len(s); i < width; i++ {
buf.WriteByte(' ')
}
}
}
// Timestamp
buf.WriteString(data.Timestamp.Load().(string)) //nolint:forcetypeassert,errcheck // Timestamp is always a string
buf.WriteString(" | ")
// Status Code with 3 fixed width, right aligned
fixedWidth(strconv.Itoa(c.Response().StatusCode()), 3, true)
buf.WriteString(" | ")
// Duration with 13 fixed width, right aligned
fixedWidth(data.Stop.Sub(data.Start).String(), 13, true)
buf.WriteString(" | ")
// Client IP with 15 fixed width, right aligned
fixedWidth(c.IP(), 15, true)
buf.WriteString(" | ")
// HTTP Method with 7 fixed width, left aligned
fixedWidth(c.Method(), 7, false)
buf.WriteString(" | ")
// Path with dynamic padding for error message, left aligned
errPadding, _ := strconv.Atoi(data.ErrPaddingStr) //nolint:errcheck // It is fine to ignore the error
fixedWidth(c.Path(), errPadding, false)
// Error message
buf.WriteString(" ")
buf.WriteString(formatErr)
buf.WriteString("\n")
}
// Write buffer to output
writeLog(cfg.Stream, buf.Bytes())
if cfg.Done != nil {
cfg.Done(c, buf.Bytes())
}
// Put buffer back to pool
bytebufferpool.Put(buf)
// End chain
return nil
}
err := logtemplate.ExecuteChains(buf, c, data, data.TemplateChain, data.LogFuncChain)
// Also write errors to the buffer
if err != nil {
buf.WriteString(err.Error())
}
writeLog(cfg.Stream, buf.Bytes())
if cfg.Done != nil {
cfg.Done(c, buf.Bytes())
}
// Put buffer back to pool
bytebufferpool.Put(buf)
return nil
}
// run something before returning the handler
func beforeHandlerFunc(cfg *Config) {
if cfg == nil {
return
}
// If colors are enabled, check terminal compatibility
if cfg.enableColors && cfg.Stream == os.Stdout {
cfg.Stream = colorable.NewColorableStdout()
if !cfg.ForceColors && (os.Getenv("TERM") == "dumb" || os.Getenv("NO_COLOR") == "1" || (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()))) {
cfg.Stream = colorable.NewNonColorable(os.Stdout)
}
}
}
// appendInt writes the decimal form of v into output without going through
// fmt boxing. The 20-byte stack scratch fits any int64; strconv.AppendInt
// only grows the slice when the formatted value exceeds that capacity, which
// cannot happen for a fixed-width int.
func appendInt(output Buffer, v int) (int, error) {
var scratch [20]byte
return output.Write(strconv.AppendInt(scratch[:0], int64(v), 10))
}
// writeLog writes a msg to w, printing a warning to stderr if the log fails.
func writeLog(w io.Writer, msg []byte) {
if _, err := w.Write(msg); err != nil {
// Write error to output
if _, writeErr := w.Write([]byte(err.Error())); writeErr != nil {
// There is something wrong with the given io.Writer
_, _ = fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", writeErr)
}
}
}