fmt.Println — prints to stdout, no metadata. log.Println — prints to stderr with timestamp, and optionally file/line info.
fmt.Println:
1fmt.Println("Processing user:", name)2// Output: Processing user Alice34// Different formatting options5fmt.Printf("Name: %s, Age: %d\n", name, age)6fmt.Fprintf(w, "Response: %v", data) // write to io.Writer
log.Println:
2024/01/15 10:30:45.os.Exit(1) on write errors.1log.Println("Processing user:", name)2// Output: 2024/01/15 10:30:45 Processing user Alice34// Configure log output5log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)6log.Println("Debug info")7// Output: 2024/01/15 10:30:45 main.go:42 Debug info89// Log to a file10f, _ := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)11defer f.Close()12log.SetOutput(f)13log.Println("This goes to file")
When to use fmt.Println:
When to use log.Println:
log.Printf for formatted output).Common mistakes:
fmt.Println for logging (no timestamps, goes to stdout).log.Println for user output (goes to stderr, has timestamps).log.Fatal which exits immediately (deferred functions won't run).slog package in Go 1.21+).