Go by Example: Logging with log Package
Go 1.23
Explore Go's standard `log` package for application logging. This example covers basic logging, configuring output flags (timestamps, file names), and redirecting logs to files, suitable for simple applications and debugging.
Code
package main
import (
"log"
"os"
)
func main() {
// Simple logging
log.Println("This is a standard log message")
log.Printf("This is a formatted log message: %d", 42)
// Configuring the logger
// Ldate: the date in the local time zone: 2009/01/23
// Ltime: the time in the local time zone: 01:23:23
// Lshortfile: full file name and line number: /a/b/c/d.go:23
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.Println("Log with flags")
// Creating a custom logger
file, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal("Failed to open log file:", err)
}
logger := log.New(file, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
logger.Println("This message goes to the file")
}Explanation
The log package provides a simple, thread-safe logging interface. While sufficient for small scripts, it lacks structured logging capabilities found in modern applications.
Key features and limitations:
- Standard Output: By default, it prints to stderr with a timestamp.
- Flags: Use
log.SetFlagsto add file names, line numbers, or microseconds. - Fatal/Panic:
log.Fatalcallsos.Exit(1)immediately, whilelog.Paniccallspanic(). - No Levels: It does not support debug/info/error levels. For that, use the new Go 1.21+
log/slogpackage or third-party libraries like Zap.
Code Breakdown
10
log.Println works just like fmt.Println but adds a timestamp prefix. It writes to the standard logger, which defaults to stderr.
11
log.Printf allows for formatted output, similar to fmt.Printf. This is useful for including variable values in your log messages.
17
log.SetFlags configures the metadata included in log messages. Ldate adds the date, Ltime adds the time, and Lshortfile adds the file name and line number (e.g., main.go:17).
21
os.OpenFile opens or creates a file for logging. O_CREATE creates it if it doesn't exist, O_WRONLY opens it for writing, and O_APPEND ensures new logs are added to the end.
23
log.Fatal logs the message and then calls os.Exit(1), terminating the program. This is commonly used for critical errors during startup.
26
log.New creates a custom logger instance. It takes an io.Writer (our file), a prefix string ("INFO: "), and flags. This allows you to have multiple loggers with different configurations.

