The `log` package in Go
The log
package in Go
The log
package in Go provides basic logging functionality. Below are some of the most commonly used functions in the log
package:
-
log.Print(v ...interface{})
- Logs a message with the default log format (typically followed by a newline).
- Example:
log.Print("This is a log message")
-
log.Println(v ...interface{})
- Logs a message with the default log format, followed by a newline.
- It’s similar to
Print
but automatically adds a newline. - Example:
log.Println("This is a log message")
-
log.Printf(format string, v ...interface{})
- Logs a formatted message, similar to
fmt.Printf
, with a default log format. - Example:
log.Printf("User %s has logged in", username)
- Logs a formatted message, similar to
-
log.Fatal(v ...interface{})
- Logs a message and then calls
os.Exit(1)
to terminate the program. It’s used for fatal errors. - Example:
if err != nil {log.Fatal("Error:", err)}
- Logs a message and then calls
-
log.Fatalln(v ...interface{})
- Similar to
log.Fatal
, but adds a newline at the end of the log message before callingos.Exit(1)
. - Example:
if err != nil {log.Fatalln("Fatal error:", err)}
- Similar to
-
log.Fatalf(format string, v ...interface{})
- Logs a formatted message and then calls
os.Exit(1)
. It’s useful when you need to format the error message before exiting. - Example:
log.Fatalf("Error: %v\n", err)
- Logs a formatted message and then calls
-
log.Panic(v ...interface{})
- Logs a message and then calls
panic()
. It’s used for non-recoverable errors that need to be logged before panicking. - Example:
if err != nil {log.Panic("Error:", err)}
- Logs a message and then calls
-
log.Panicln(v ...interface{})
- Similar to
log.Panic
, but adds a newline after the log message before callingpanic()
. - Example:
log.Panicln("This is a panic message")
- Similar to
-
log.Panicf(format string, v ...interface{})
- Similar to
log.Panic
, but with formatted output. - Example:
log.Panicf("Something went wrong: %v", err)
- Similar to
-
log.SetFlags(flag int)
- Sets the flags for the default logger. Common flags include
log.Ldate
,log.Ltime
,log.Lshortfile
, etc., which control the output format of log messages. - Example:
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
- Sets the flags for the default logger. Common flags include
-
log.SetPrefix(prefix string)
- Sets a prefix to be included at the start of every log message.
- Example:
log.SetPrefix("[INFO] ")
These functions provide a simple interface for logging messages in Go applications.