fmt.Println — formatted output to stdout without metadata. log.Println — logging to stderr with timestamp and optional file/line info.
fmt.Println details:
os.Stdout.(n int, err error).1// Basic usage2fmt.Println("User:", name, "Age:", age)3// Output: User: Alice Age: 3045// Formatting6fmt.Printf("User: %s (age %d)\n", name, age)7fmt.Sprintf("User: %s", name) // returns string89// Write to custom writer10fmt.Fprintf(os.Stderr, "Warning: %s\n", msg)
log.Println details:
os.Stderr.os.Exit(1) on write failure.1// Default behavior2log.Println("Server starting on port 8080")3// Output: 2024/01/15 10:30:45 Server starting on port 808045// With file info6log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)7log.Println("Request processed")8// Output: 2024/01/15 10:30:45 main.go:42 Request processed910// Log to file11f, _ := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)12defer f.Close()13log.SetOutput(f)14log.Println("This goes to file")
Structured logging (Go 1.21+):
1import "log/slog"23slog.Info("User logged in", "user_id", 123, "ip", "192.168.1.1")4slog.Error("Database connection failed", "error", err)
When to use fmt:
When to use log:
Common mistakes:
fmt.Println for logs (no timestamps, hard to filter).log.Println for user output (stderr, has timestamps).log.Fatal which exits immediately.