-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtools.go
292 lines (251 loc) · 6.9 KB
/
tools.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
package log
import (
"bytes"
"encoding/json"
"fmt"
"io"
"runtime"
"strings"
"time"
"github.com/goloop/g"
"github.com/goloop/log/level"
)
// The stackFrame contains the top-level trace information
// where the logging method was called.
type stackFrame struct {
FileLine int // line number
FuncName string // function name
FuncAddress uintptr // address of the function
FilePath string // file path
}
// The ioCopy function is used to copy the output of a reader
// to a channel.
func ioCopy(r io.Reader, c chan string) {
var buf bytes.Buffer
io.Copy(&buf, r)
c <- buf.String()
}
// The getStackFrame returns the stack slice. The skip argument
// is the number of stack frames to skip before taking a slice.
func getStackFrame(skip int) *stackFrame {
sf := &stackFrame{}
// Return program counters of function invocations on
// the calling goroutine's stack and skipping function
// call frames inside *Log.
pc := make([]uintptr, skip+1) // program counters
runtime.Callers(skip, pc)
// Get a function at an address on the stack.
fn := runtime.FuncForPC(pc[0])
// Get name, path and line of the file.
sf.FuncName = fn.Name()
sf.FuncAddress = fn.Entry()
sf.FilePath, sf.FileLine = fn.FileLine(pc[0])
if r := strings.Split(sf.FuncName, "."); len(r) > 0 {
sf.FuncName = r[len(r)-1]
}
return sf
}
// The cutFilePath cuts the path to the file to the
// specified number of sections.
func cutFilePath(n int, path string) string {
sections := strings.Split(path, "/")
// If there are fewer or equal sections than n,
// return the path unmodified.
if len(sections) <= n+1 {
return path
}
return ".../" + strings.Join(sections[len(sections)-n:], "/")
}
// The textMessage creates a text message.
func textMessage(
p string,
l level.Level,
t time.Time,
o *Output,
sf *stackFrame,
f string,
a ...any,
) string {
// Generate log header.
// The text before of the user's message, which includes the
// prefix, the date and time of the event, the message level,
// and additional format data (file, function, line etc.).
sb := strings.Builder{}
// Logger prefix.
if p != "" {
sb.WriteString(p)
sb.WriteString(o.Space)
}
// Timestamp.
sb.WriteString(t.Format(o.TimestampFormat))
sb.WriteString(o.Space)
// Level name.
labels := level.Labels
if o.WithColor.IsTrue() && runtime.GOOS != "windows" {
labels = level.ColorLabels
}
if v, ok := labels[l]; ok {
sb.WriteString(fmt.Sprintf(o.LevelFormat, v))
sb.WriteString(o.Space)
}
// File path.
// The FullPath takes precedence over ShortPath.
if o.Layouts.FilePath() {
if o.Layouts.FullFilePath() {
sb.WriteString(sf.FilePath)
} else {
sb.WriteString(cutFilePath(shortPathSections, sf.FilePath))
}
if o.Layouts.LineNumber() {
sb.WriteString(fmt.Sprintf(":%d", sf.FileLine))
}
sb.WriteString(o.Space)
}
// Line number.
if o.Layouts.LineNumber() && !o.Layouts.FilePath() {
sb.WriteString(fmt.Sprintf("%d%s", sf.FileLine, o.Space))
}
// Function name.
if o.Layouts.FuncName() {
sb.WriteString(sf.FuncName)
if o.Layouts.FuncAddress() {
sb.WriteString(fmt.Sprintf(":%#x", sf.FuncAddress))
}
sb.WriteString(o.Space)
}
// Function address.
if o.Layouts.FuncAddress() && !o.Layouts.FuncName() {
sb.WriteString(fmt.Sprintf("%#x%s", sf.FuncAddress, o.Space))
}
// Add message formatting.
var msg string
switch {
case f == "":
fallthrough
case f == formatPrint:
// For messages that are output on the same line, the task of
// separating the messages falls on the user. We don't need to
// add extra characters to user messages.
// msg = fmt.Sprintf("%s%s%s", sb.String(), fmt.Sprint(a...), o.Space)
msg = fmt.Sprintf("%s%s", sb.String(), fmt.Sprint(a...))
case f == formatPrintln:
msg = fmt.Sprintf("%s%s", sb.String(), fmt.Sprintln(a...))
default:
msg = fmt.Sprintf("%s%s", sb.String(), fmt.Sprintf(f, a...))
}
return msg
}
// The objectMessage creates a JSON message.
func objectMessage(
p string,
l level.Level,
t time.Time,
o *Output,
sf *stackFrame,
f string,
a ...any,
) string {
// Output object.
// A general structure for outputting a log in JSON format.
obj := struct {
Prefix string `json:"prefix,omitempty"`
Level string `json:"level,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
Message string `json:"message,omitempty"`
FilePath string `json:"filePath,omitempty"`
LineNumber int `json:"lineNumber,omitempty"`
FuncName string `json:"funcName,omitempty"`
FuncAddress string `json:"funcAddress,omitempty"`
}{}
// Logger prefix.
if p != "" {
obj.Prefix = p
}
// Timestamp.
obj.Timestamp = t.Format(o.TimestampFormat)
// Level label.
if v, ok := level.Labels[l]; ok {
obj.Level = v
}
// File path, full path only.
if o.Layouts.FilePath() {
obj.FilePath = sf.FilePath
}
// Function name.
if o.Layouts.FuncName() {
obj.FuncName = sf.FuncName
}
// Function address.
if o.Layouts.FuncAddress() {
obj.FuncAddress = fmt.Sprintf("%#x", sf.FuncAddress)
}
// Line number.
if o.Layouts.LineNumber() {
obj.LineNumber = sf.FileLine
}
// Clean message for default -ln format.
// Add message formatting.
switch {
case f == "":
fallthrough
case f == formatPrint:
obj.Message = fmt.Sprint(a...)
case f == formatPrintln:
obj.Message = strings.TrimSuffix(fmt.Sprintln(a...), "\n")
default:
obj.Message = fmt.Sprintf(f, a...)
}
// Marshal object to JSON.
data, err := json.Marshal(obj)
data = g.If(err != nil, []byte{}, data)
// Add JSON formatting.
var msg string
switch {
case f == "":
fallthrough
case f == formatPrint:
msg = string(data)
default: // for formatStrLn and others
msg = fmt.Sprintf("%s\n", data)
}
// Add space if necessary.
if o.Space != "" {
msg += o.Space
}
return msg
}
/*
// The getWriterID returns the unique ID of the object
// in the io.Writer interface.
//
// To identify duplicate objects of the os.Writer interface, the actual
// address of the object in memory is used. This does not guarantee 100%
// verification of uniqueness, but there is no need for it.
//
// Usually, these are 2-3 files for logging, which are added almost
// simultaneously, which guarantees a stable address of the object at
// the time of adding it to the list of outputs. And the issue of
// duplicates must be monitored by the developer who uses the logger.
//
// Therefore, checking for duplicates is a useful auxiliary function
// for detecting "stupid" logger creation errors.
func getWriterID(w io.Writer) uintptr {
switch v := w.(type) {
case *os.File:
return reflect.ValueOf(v).Pointer()
case *bytes.Buffer:
return reflect.ValueOf(v).Pointer()
case *strings.Builder:
return reflect.ValueOf(v).Pointer()
case *bufio.Writer:
return reflect.ValueOf(v).Pointer()
case *gzip.Writer:
return reflect.ValueOf(v).Pointer()
case *io.PipeWriter:
return reflect.ValueOf(v).Pointer()
}
// Unknown type.
// Get the address of the interface itself.
return reflect.ValueOf(w).Pointer()
}
*/