Debian Codegraph @

src/log/log.go

raw
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package log implements a simple logging package. It defines a type, [Logger],
6 // with methods for formatting output. It also has a predefined 'standard'
7 // Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and
8 // Panic[f|ln], which are easier to use than creating a Logger manually.
9 // That logger writes to standard error and prints the date and time
10 // of each logged message.
11 // Every log message is output on a separate line: if the message being
12 // printed does not end in a newline, the logger will add one.
13 // The Fatal functions call [os.Exit](1) after writing the log message.
14 // The Panic functions call panic after writing the log message.
15 package log
16
17 import (
18 "fmt"
19 "io"
20 "log/internal"
21 "os"
22 "runtime"
23 "sync"
24 "sync/atomic"
25 "time"
26 )
27
28 // These flags define which text to prefix to each log entry generated by the [Logger].
29 // Bits are or'ed together to control what's printed.
30 // With the exception of the Lmsgprefix flag, there is no
31 // control over the order they appear (the order listed here)
32 // or the format they present (as described in the comments).
33 // The prefix is followed by a colon only when Llongfile or Lshortfile
34 // is specified.
35 // For example, flags Ldate | Ltime (or LstdFlags) produce,
36 //
37 // 2009/01/23 01:23:23 message
38 //
39 // while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
40 //
41 // 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
42 const (
43 Ldate = 1 << iota // the date in the local time zone: 2009/01/23
44 Ltime // the time in the local time zone: 01:23:23
45 Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.
46 Llongfile // full file name and line number: /a/b/c/d.go:23
47 Lshortfile // final file name element and line number: d.go:23. overrides Llongfile
48 LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone
49 Lmsgprefix // move the "prefix" from the beginning of the line to before the message
50 LstdFlags = Ldate | Ltime // initial values for the standard logger
51 )
52
53 // A Logger represents an active logging object that generates lines of
54 // output to an [io.Writer]. Each logging operation makes a single call to
55 // the Writer's Write method. A Logger can be used simultaneously from
56 // multiple goroutines; it guarantees to serialize access to the Writer.
57 type Logger struct {
58 outMu sync.Mutex
59 out io.Writer // destination for output
60
61 prefix atomic.Pointer[string] // prefix on each line to identify the logger (but see Lmsgprefix)
62 flag atomic.Int32 // properties
63 isDiscard atomic.Bool
64 }
65
66 // New creates a new [Logger]. The out variable sets the
67 // destination to which log data will be written.
68 // The prefix appears at the beginning of each generated log line, or
69 // after the log header if the [Lmsgprefix] flag is provided.
70 // The flag argument defines the logging properties.
71 func New(out io.Writer, prefix string, flag int) *Logger {
72 l := new(Logger)
73 l.SetOutput(out)
74 l.SetPrefix(prefix)
75 l.SetFlags(flag)
76 return l
77 }
78
79 // SetOutput sets the output destination for the logger.
80 func (l *Logger) SetOutput(w io.Writer) {
81 l.outMu.Lock()
82 defer l.outMu.Unlock()
83 l.out = w
84 l.isDiscard.Store(w == io.Discard)
85 }
86
87 var std = New(os.Stderr, "", LstdFlags)
88
89 // Default returns the standard logger used by the package-level output functions.
90 func Default() *Logger { return std }
91
92 // Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding.
93 func itoa(buf *[]byte, i int, wid int) {
94 // Assemble decimal in reverse order.
95 var b [20]byte
96 bp := len(b) - 1
97 for i >= 10 || wid > 1 {
98 wid--
99 q := i / 10
100 b[bp] = byte('0' + i - q*10)
101 bp--
102 i = q
103 }
104 // i < 10
105 b[bp] = byte('0' + i)
106 *buf = append(*buf, b[bp:]...)
107 }
108
109 // formatHeader writes log header to buf in following order:
110 // - l.prefix (if it's not blank and Lmsgprefix is unset),
111 // - date and/or time (if corresponding flags are provided),
112 // - file and line number (if corresponding flags are provided),
113 // - l.prefix (if it's not blank and Lmsgprefix is set).
114 func formatHeader(buf *[]byte, t time.Time, prefix string, flag int, file string, line int) {
115 if flag&Lmsgprefix == 0 {
116 *buf = append(*buf, prefix...)
117 }
118 if flag&(Ldate|Ltime|Lmicroseconds) != 0 {
119 if flag&LUTC != 0 {
120 t = t.UTC()
121 }
122 if flag&Ldate != 0 {
123 year, month, day := t.Date()
124 itoa(buf, year, 4)
125 *buf = append(*buf, '/')
126 itoa(buf, int(month), 2)
127 *buf = append(*buf, '/')
128 itoa(buf, day, 2)
129 *buf = append(*buf, ' ')
130 }
131 if flag&(Ltime|Lmicroseconds) != 0 {
132 hour, min, sec := t.Clock()
133 itoa(buf, hour, 2)
134 *buf = append(*buf, ':')
135 itoa(buf, min, 2)
136 *buf = append(*buf, ':')
137 itoa(buf, sec, 2)
138 if flag&Lmicroseconds != 0 {
139 *buf = append(*buf, '.')
140 itoa(buf, t.Nanosecond()/1e3, 6)
141 }
142 *buf = append(*buf, ' ')
143 }
144 }
145 if flag&(Lshortfile|Llongfile) != 0 {
146 if flag&Lshortfile != 0 {
147 short := file
148 for i := len(file) - 1; i > 0; i-- {
149 if file[i] == '/' {
150 short = file[i+1:]
151 break
152 }
153 }
154 file = short
155 }
156 *buf = append(*buf, file...)
157 *buf = append(*buf, ':')
158 itoa(buf, line, -1)
159 *buf = append(*buf, ": "...)
160 }
161 if flag&Lmsgprefix != 0 {
162 *buf = append(*buf, prefix...)
163 }
164 }
165
166 var bufferPool = sync.Pool{New: func() any { return new([]byte) }}
167
168 func getBuffer() *[]byte {
169 p := bufferPool.Get().(*[]byte)
170 *p = (*p)[:0]
171 return p
172 }
173
174 func putBuffer(p *[]byte) {
175 // Proper usage of a sync.Pool requires each entry to have approximately
176 // the same memory cost. To obtain this property when the stored type
177 // contains a variably-sized buffer, we add a hard limit on the maximum buffer
178 // to place back in the pool.
179 //
180 // See https://go.dev/issue/23199
181 if cap(*p) > 64<<10 {
182 *p = nil
183 }
184 bufferPool.Put(p)
185 }
186
187 // Output writes the output for a logging event. The string s contains
188 // the text to print after the prefix specified by the flags of the
189 // Logger. A newline is appended if the last character of s is not
190 // already a newline. Calldepth is used to recover the PC and is
191 // provided for generality, although at the moment on all pre-defined
192 // paths it will be 2.
193 func (l *Logger) Output(calldepth int, s string) error {
194 return l.output(0, calldepth+1, func(b []byte) []byte { // +1 for this frame.
195 return append(b, s...)
196 })
197 }
198
199 // output can take either a calldepth or a pc to get source line information.
200 // It uses the pc if it is non-zero.
201 func (l *Logger) output(pc uintptr, calldepth int, appendOutput func([]byte) []byte) error {
202 if l.isDiscard.Load() {
203 return nil
204 }
205
206 now := time.Now() // get this early.
207
208 // Load prefix and flag once so that their value is consistent within
209 // this call regardless of any concurrent changes to their value.
210 prefix := l.Prefix()
211 flag := l.Flags()
212
213 var file string
214 var line int
215 if flag&(Lshortfile|Llongfile) != 0 {
216 if pc == 0 {
217 var ok bool
218 _, file, line, ok = runtime.Caller(calldepth)
219 if !ok {
220 file = "???"
221 line = 0
222 }
223 } else {
224 fs := runtime.CallersFrames([]uintptr{pc})
225 f, _ := fs.Next()
226 file = f.File
227 if file == "" {
228 file = "???"
229 }
230 line = f.Line
231 }
232 }
233
234 buf := getBuffer()
235 defer putBuffer(buf)
236 formatHeader(buf, now, prefix, flag, file, line)
237 *buf = appendOutput(*buf)
238 if len(*buf) == 0 || (*buf)[len(*buf)-1] != '\n' {
239 *buf = append(*buf, '\n')
240 }
241
242 l.outMu.Lock()
243 defer l.outMu.Unlock()
244 _, err := l.out.Write(*buf)
245 return err
246 }
247
248 func init() {
249 internal.DefaultOutput = func(pc uintptr, data []byte) error {
250 return std.output(pc, 0, func(buf []byte) []byte {
251 return append(buf, data...)
252 })
253 }
254 }
255
256 // Print calls l.Output to print to the logger.
257 // Arguments are handled in the manner of [fmt.Print].
258 func (l *Logger) Print(v ...any) {
259 l.output(0, 2, func(b []byte) []byte {
260 return fmt.Append(b, v...)
261 })
262 }
263
264 // Printf calls l.Output to print to the logger.
265 // Arguments are handled in the manner of [fmt.Printf].
266 func (l *Logger) Printf(format string, v ...any) {
267 l.output(0, 2, func(b []byte) []byte {
268 return fmt.Appendf(b, format, v...)
269 })
270 }
271
272 // Println calls l.Output to print to the logger.
273 // Arguments are handled in the manner of [fmt.Println].
274 func (l *Logger) Println(v ...any) {
275 l.output(0, 2, func(b []byte) []byte {
276 return fmt.Appendln(b, v...)
277 })
278 }
279
280 // Fatal is equivalent to l.Print() followed by a call to [os.Exit](1).
281 func (l *Logger) Fatal(v ...any) {
282 l.output(0, 2, func(b []byte) []byte {
283 return fmt.Append(b, v...)
284 })
285 os.Exit(1)
286 }
287
288 // Fatalf is equivalent to l.Printf() followed by a call to [os.Exit](1).
289 func (l *Logger) Fatalf(format string, v ...any) {
290 l.output(0, 2, func(b []byte) []byte {
291 return fmt.Appendf(b, format, v...)
292 })
293 os.Exit(1)
294 }
295
296 // Fatalln is equivalent to l.Println() followed by a call to [os.Exit](1).
297 func (l *Logger) Fatalln(v ...any) {
298 l.output(0, 2, func(b []byte) []byte {
299 return fmt.Appendln(b, v...)
300 })
301 os.Exit(1)
302 }
303
304 // Panic is equivalent to l.Print() followed by a call to panic().
305 func (l *Logger) Panic(v ...any) {
306 s := fmt.Sprint(v...)
307 l.output(0, 2, func(b []byte) []byte {
308 return append(b, s...)
309 })
310 panic(s)
311 }
312
313 // Panicf is equivalent to l.Printf() followed by a call to panic().
314 func (l *Logger) Panicf(format string, v ...any) {
315 s := fmt.Sprintf(format, v...)
316 l.output(0, 2, func(b []byte) []byte {
317 return append(b, s...)
318 })
319 panic(s)
320 }
321
322 // Panicln is equivalent to l.Println() followed by a call to panic().
323 func (l *Logger) Panicln(v ...any) {
324 s := fmt.Sprintln(v...)
325 l.output(0, 2, func(b []byte) []byte {
326 return append(b, s...)
327 })
328 panic(s)
329 }
330
331 // Flags returns the output flags for the logger.
332 // The flag bits are [Ldate], [Ltime], and so on.
333 func (l *Logger) Flags() int {
334 return int(l.flag.Load())
335 }
336
337 // SetFlags sets the output flags for the logger.
338 // The flag bits are [Ldate], [Ltime], and so on.
339 func (l *Logger) SetFlags(flag int) {
340 l.flag.Store(int32(flag))
341 }
342
343 // Prefix returns the output prefix for the logger.
344 func (l *Logger) Prefix() string {
345 if p := l.prefix.Load(); p != nil {
346 return *p
347 }
348 return ""
349 }
350
351 // SetPrefix sets the output prefix for the logger.
352 func (l *Logger) SetPrefix(prefix string) {
353 l.prefix.Store(&prefix)
354 }
355
356 // Writer returns the output destination for the logger.
357 func (l *Logger) Writer() io.Writer {
358 l.outMu.Lock()
359 defer l.outMu.Unlock()
360 return l.out
361 }
362
363 // SetOutput sets the output destination for the standard logger.
364 func SetOutput(w io.Writer) {
365 std.SetOutput(w)
366 }
367
368 // Flags returns the output flags for the standard logger.
369 // The flag bits are [Ldate], [Ltime], and so on.
370 func Flags() int {
371 return std.Flags()
372 }
373
374 // SetFlags sets the output flags for the standard logger.
375 // The flag bits are [Ldate], [Ltime], and so on.
376 func SetFlags(flag int) {
377 std.SetFlags(flag)
378 }
379
380 // Prefix returns the output prefix for the standard logger.
381 func Prefix() string {
382 return std.Prefix()
383 }
384
385 // SetPrefix sets the output prefix for the standard logger.
386 func SetPrefix(prefix string) {
387 std.SetPrefix(prefix)
388 }
389
390 // Writer returns the output destination for the standard logger.
391 func Writer() io.Writer {
392 return std.Writer()
393 }
394
395 // These functions write to the standard logger.
396
397 // Print calls Output to print to the standard logger.
398 // Arguments are handled in the manner of [fmt.Print].
399 func Print(v ...any) {
400 std.output(0, 2, func(b []byte) []byte {
401 return fmt.Append(b, v...)
402 })
403 }
404
405 // Printf calls Output to print to the standard logger.
406 // Arguments are handled in the manner of [fmt.Printf].
407 func Printf(format string, v ...any) {
408 std.output(0, 2, func(b []byte) []byte {
409 return fmt.Appendf(b, format, v...)
410 })
411 }
412
413 // Println calls Output to print to the standard logger.
414 // Arguments are handled in the manner of [fmt.Println].
415 func Println(v ...any) {
416 std.output(0, 2, func(b []byte) []byte {
417 return fmt.Appendln(b, v...)
418 })
419 }
420
421 // Fatal is equivalent to [Print] followed by a call to [os.Exit](1).
422 func Fatal(v ...any) {
423 std.output(0, 2, func(b []byte) []byte {
424 return fmt.Append(b, v...)
425 })
426 os.Exit(1)
427 }
428
429 // Fatalf is equivalent to [Printf] followed by a call to [os.Exit](1).
430 func Fatalf(format string, v ...any) {
431 std.output(0, 2, func(b []byte) []byte {
432 return fmt.Appendf(b, format, v...)
433 })
434 os.Exit(1)
435 }
436
437 // Fatalln is equivalent to [Println] followed by a call to [os.Exit](1).
438 func Fatalln(v ...any) {
439 std.output(0, 2, func(b []byte) []byte {
440 return fmt.Appendln(b, v...)
441 })
442 os.Exit(1)
443 }
444
445 // Panic is equivalent to [Print] followed by a call to panic().
446 func Panic(v ...any) {
447 s := fmt.Sprint(v...)
448 std.output(0, 2, func(b []byte) []byte {
449 return append(b, s...)
450 })
451 panic(s)
452 }
453
454 // Panicf is equivalent to [Printf] followed by a call to panic().
455 func Panicf(format string, v ...any) {
456 s := fmt.Sprintf(format, v...)
457 std.output(0, 2, func(b []byte) []byte {
458 return append(b, s...)
459 })
460 panic(s)
461 }
462
463 // Panicln is equivalent to [Println] followed by a call to panic().
464 func Panicln(v ...any) {
465 s := fmt.Sprintln(v...)
466 std.output(0, 2, func(b []byte) []byte {
467 return append(b, s...)
468 })
469 panic(s)
470 }
471
472 // Output writes the output for a logging event. The string s contains
473 // the text to print after the prefix specified by the flags of the
474 // Logger. A newline is appended if the last character of s is not
475 // already a newline. Calldepth is the count of the number of
476 // frames to skip when computing the file name and line number
477 // if [Llongfile] or [Lshortfile] is set; a value of 1 will print the details
478 // for the caller of Output.
479 func Output(calldepth int, s string) error {
480 return std.output(0, calldepth+1, func(b []byte) []byte { // +1 for this frame.
481 return append(b, s...)
482 })
483 }