log.Fatal — logs a message and calls os.Exit(1) (program terminates immediately). log.Panic — logs a message and calls panic() (deferred functions run).
log.Fatal behavior:
os.Exit(1) immediately.1func main() {2 defer fmt.Println("This will NOT print")34 if err := startServer(); err != nil {5 log.Fatal("Failed to start server: ", err)6 }7}8// Output: 2024/01/15 10:30:45 Failed to start server: connection refused9// Deferred fmt.Println never runs10// Program exits with code 1
log.Panic behavior:
panic() with the formatted message.recover().1func main() {2 defer func() {3 if r := recover(); r != nil {4 fmt.Println("Recovered:", r)5 }6 }()78 defer fmt.Println("This WILL print")910 log.Panic("Something went wrong")11}12// Output:13// 2024/01/15 10:30:45 Something went wrong14// This WILL print15// Recovered: Something went wrong
When to use log.Fatal:
When to use log.Panic:
Common mistakes:
log.Fatal in library code (forces caller to handle termination).log.Panic without a recover() somewhere up the stack.log.Fatal doesn't run deferred functions (data loss risk).log.Fatal with error returns (caller never sees the error).