log
Before You Start
- Applies to: Go 1.21+ (examples verified with Go 1.22;
log/slogrequires Go 1.21+) · Prerequisites: Base: Functions · Read time: about 8 min
Go language standard library log package implements simple logging.
go
func main() {
log.Println("Log message")
log.Panicln("Panic log")
log.Fatalln("Error log")
}Fatal will call os.Exit(1) after writing the log message, while panic will throw a panic.
Prefix
go
func (l *Logger) Prefix() string // Get prefix
func (l *Logger) SetPrefix(prefix string) // Set prefixExample:
go
func main() {
log.SetPrefix("[main]")
log.Println("Log message")
log.Panicln("Panic log")
}Flag
Methods:
go
func (l *Logger) Flags() int // Access
func (l *Logger) SetFlags(flag int) // SetConstants:
go
const (
Ldate = 1 << iota // Date
Ltime // Time
Lmicroseconds // Microseconds
Llongfile // Full file name
Lshortfile // Short file name
LUTC // Timezone
Lmsgprefix // Prefix
LstdFlags = Ldate | Ltime // Initial value
)Example:
go
func main() {
log.SetFlags(log.Lshortfile | log.Lmicroseconds | log.Lmsgprefix | log.Ldate | log.Ltime)
log.Println("Log message")
log.Panicln("Panic log")
}Of course, you can also use log.SetOutput(w io.Writer) to set the log output path, or create your own instance through the New method.
go
func New(out io.Writer, prefix string, flag int) *LoggerIn short, the standard library's log package does not provide complete functionality. We usually use more complete third-party logging packages, such as zap, etc.
Complete Example
The program below runs as-is: copy it into a file and execute go run main.go, or paste it into the Go Playground.
go
package main
import (
"bytes"
"fmt"
"log"
)
func main() {
var buf bytes.Buffer
logger := log.New(&buf, "app: ", 0)
logger.Println("started")
logger.Printf("user=%s", "gopher")
fmt.Print(buf.String())
}Expected output:
text
app: started
app: user=gopherCommon Pitfalls
log.Fatalcallsos.Exit(1). Deferred cleanup does not run; keep it out of library code.- The default logger writes to stderr. Redirect with
log.SetOutputor instantiate your ownlog.Logger. - Timestamps need flags.
LstdFlagsadds date/time,Lshortfileadds the caller location. - Loggers are concurrency-safe. Sharing one
*log.Loggeracross goroutines is fine; abytes.Buffertarget is not. - Consider
log/slog(Go 1.21+). Structured logging is now part of the standard library and integrates with context.
Change Log
- 2026-10-14: Added "Before You Start" notes, a complete runnable example with expected output, common pitfalls, and this change log.
