To handle and log errors with the log
package in Go, you can follow these steps:
import "log"
log.SetOutput(os.Stdout) // set output to standard output
// OR
file, err := os.OpenFile("logfile.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
log.SetOutput(file) // set output to a file
log.SetPrefix("ERROR: ")
log.SetFlags(log.LstdFlags | log.Lmicroseconds) // Use desired flags
err := SomeFunction()
if err != nil {
log.Printf("Error occurred: %v", err)
// or
log.Fatal("Fatal error occurred: ", err)
// or
log.Panic("Panic occurred: ", err)
}
You can choose one of the following log functions based on your requirements:
log.Print(v ...interface{})
or log.Println(v ...interface{})
log.Printf(format string, v ...interface{})
log.Fatal(v ...interface{})
or log.Fatalln(v ...interface{})
log.Fatalf(format string, v ...interface{})
log.Panic(v ...interface{})
or log.Panicln(v ...interface{})
log.Panicf(format string, v ...interface{})
With these steps, you can handle and log errors using the log
package in Go.