[Golang (Go)] Use log package to output log
log
Package log
implements a simple logging package. It defines a type, Logger
, with methods for formatting output. It also has a predefined ‘standard’ Logger accessible through helper functions Print[f|ln]
, Fatal[f|ln]
, and Panic[f|ln]
, which are easier to use than creating a Logger manually. That logger writes to standard error and prints the date and time of each logged message. Every log message is output on a separate line: if the message being printed does not end in a newline, the logger will add one. The Fatal
functions call os.Exit(1)
after writing the log message. The Panic
functions call panic
after writing the log message.
Example
1 | // main.go |
Run it.
1 | go run main.go |
Flags
These flags define which text to prefix to each log entry generated by the Logger. Bits are or’ed together to control what’s printed. With the exception of the Lmsgprefix flag, there is no control over the order they appear (the order listed here) or the format they present (as described in the comments). The prefix is followed by a colon only when Llongfile or Lshortfile is specified. For example, flags Ldate | Ltime (or LstdFlags) produce,
1 | 2009/01/23 01:23:23 message |
while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
1 | 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message |
Example
1 | // main.go |
Run it.
1 | go run main.go |
See Flags const - https://golang.org/src/log/log.go?s=8098:8126#L233 to learn more.
1 | // These flags define which text to prefix to each log entry generated by the Logger. |
Prefix
SetPrefix
sets the output prefix for the logger.
Example
1 | // main.go |
Run it.
1 | go run main.go |
Custome Log
function New
creates a new Logger
. The out
variable sets the destination to which log data will be written. The prefix
appears at the beginning of each generated log line, or after the log header if the Lmsgprefix flag is provided. The flag
argument defines the logging properties.
1 | func New(out io.Writer, prefix string, flag int) *Logger |
New Log
The follow code outputs the log to a bytes.Buffer
1 | buf := &bytes.Buffer{} |
Multi-destination Output
We can use io.MultiWriter
to achieve multi-destination output. Below we will output the log to standard output, bytes.Buffer and file at the same time.
1 | writer1 := &bytes.Buffer{} |
References
[1] log - The Go Programming Language - https://golang.org/pkg/log/
[3] [Go 每日一库之 log - 大俊的博客 - https://darjun.github.io/2020/02/07/godailylib/log/]