The log.Panic function in Golang is part of the log package and is used to log a message and then immediately trigger a panic in the program. This function is particularly useful when you want to log an error or critical condition and ensure that the program’s normal execution stops, allowing the panic to propagate up the call stack.
Table of Contents
- Introduction
log.PanicFunction Syntax- Examples
- Basic Usage
- Logging and Panicking on Critical Errors
- Using
log.Panicin Goroutines
- Real-World Use Case Example
- Conclusion
Introduction
The log.Panic function provides a mechanism for logging an error message and then triggering a panic, which stops the normal flow of the program. Unlike log.Fatal, which terminates the program immediately, log.Panic allows the panic to be recovered if needed, giving you the flexibility to handle the error further up the call stack or to allow the program to crash.
log.Panic Function Syntax
The syntax for the log.Panic function is as follows:
func Panic(v ...interface{})
Parameters:
v ...interface{}: The message or variables to be logged. This is a variadic parameter, meaning you can pass multiple arguments of any type.
Behavior:
- Logs the message: The function logs the provided message(s) using the standard logger.
- Triggers a panic: After logging the message, the function calls
panic, which stops the normal execution of the program and begins unwinding the stack.
Examples
Basic Usage
This example demonstrates how to use log.Panic to log a message and trigger a panic.
Example
package main
import (
"log"
)
func main() {
log.Panic("A critical error occurred!")
}
Output:
2024/08/10 12:34:56 A critical error occurred!
panic: A critical error occurred!
Explanation:
- The
log.Panicfunction logs the message "A critical error occurred!" and then triggers a panic, which stops the normal flow of the program and produces a stack trace.
Logging and Panicking on Critical Errors
This example shows how to use log.Panic to handle critical errors that should cause the program to stop.
Example
package main
import (
"log"
"os"
)
func main() {
fileName := "nonexistentfile.txt"
file, err := os.Open(fileName)
if err != nil {
log.Panic("Error opening file:", fileName, err)
}
defer file.Close()
// Additional file operations...
}
Output:
2024/08/10 12:34:56 Error opening file: nonexistentfile.txt open nonexistentfile.txt: no such file or directory
panic: Error opening file: nonexistentfile.txt open nonexistentfile.txt: no such file or directory
Explanation:
- The
log.Panicfunction logs the error message along with the file name and error details, and then triggers a panic, allowing the program to stop execution and print a stack trace.
Using log.Panic in Goroutines
This example demonstrates how to use log.Panic within a goroutine to log an error and trigger a panic that can be recovered.
Example
package main
import (
"log"
"sync"
)
func worker(wg *sync.WaitGroup) {
defer wg.Done()
defer func() {
if r := recover(); r != nil {
log.Println("Recovered from panic:", r)
}
}()
log.Panic("A critical error in worker!")
}
func main() {
var wg sync.WaitGroup
wg.Add(1)
go worker(&wg)
wg.Wait()
log.Println("Program finished.")
}
Output:
2024/08/10 12:34:56 A critical error in worker!
panic: A critical error in worker!
2024/08/10 12:34:56 Recovered from panic: A critical error in worker!
2024/08/10 12:34:56 Program finished.
Explanation:
- The
log.Panicfunction triggers a panic inside the goroutine. Therecoverfunction catches the panic, allowing the program to handle the error and continue.
Real-World Use Case Example: Panic on Unrecoverable Configuration Error
A practical use case for log.Panic is handling unrecoverable errors, such as failing to load essential configuration data.
Example: Handling a Fatal Configuration Error
package main
import (
"encoding/json"
"log"
"os"
)
type Config struct {
Port int `json:"port"`
}
func loadConfig(filename string) Config {
file, err := os.Open(filename)
if err != nil {
log.Panic("Failed to open config file:", filename, err)
}
defer file.Close()
var config Config
err = json.NewDecoder(file).Decode(&config)
if err != nil {
log.Panic("Failed to decode config file:", filename, err)
}
return config
}
func main() {
config := loadConfig("config.json")
log.Printf("Server starting on port %d", config.Port)
}
Explanation:
- The
log.Panicfunction is used to handle critical errors that occur when loading and decoding the configuration file. If the file cannot be opened or decoded, the program logs the error and triggers a panic, stopping further execution.
Conclusion
The log.Panic function in Go is used for logging error messages and triggering a panic when a critical error occurs. Unlike log.Fatal, log.Panic allows the panic to be recovered, giving you the flexibility to handle the error or stop the program’s execution. Whether you’re dealing with critical configuration errors, handling errors in goroutines, or other scenarios where immediate attention is needed, log.Panic provides a way to ensure that your program responds appropriately to serious issues.