Master Go’s log Package: Essential Techniques for Effective Logging
This article provides a comprehensive guide to Go's standard library log package, covering basic functions, output redirection, formatting options, custom logger creation, simple log‑level management, and practical tips for using logging effectively in production Go applications.
Introduction
Go’s standard library includes the log package, which provides simple yet powerful logging capabilities essential for debugging, troubleshooting, and runtime monitoring. This article explains the package’s features and usage techniques.
log Package Overview
The log package offers basic logging functions, supports message formatting, output destination configuration, and log level management.
Basic Usage
The core functions are:
log.Print() log.Printf() log.Println() log.Fatal() log.Fatalf() log.Fatalln() log.Panic() log.Panicf() log.Panicln()Example:
package main
import (
"log"
)
func main() {
log.Print("This is a log message")
log.Printf("This is a formatted log message: %d", 42)
log.Println("This is a log message with a newline")
// log.Fatal("This is a fatal log message")
// log.Fatalf("This is a formatted fatal log message: %d", 42)
// log.Fatalln("This is a fatal log message with a newline")
// log.Panic("This is a panic log message")
// log.Panicf("This is a formatted panic log message: %d", 42)
// log.Panicln("This is a panic log message with a newline")
}Output:
2024/05/20 21:43:23 This is a log message
2024/05/20 21:43:23 This is a formatted log message: 42
2024/05/20 21:43:23 This is a log message with a newlineLog Output Destination
By default logs go to standard error. Use log.SetOutput() to redirect to a file or custom writer.
package main
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
defer file.Close()
log.SetOutput(file)
log.Println("This is a log message written to a file")
} cat ./app.log
2024/05/20 21:44:11 This is a log message written to a fileLog Formatting
Customize prefix and flags with log.SetPrefix() and log.SetFlags(). Common flags include log.Ldate, log.Ltime, log.Lmicroseconds, log.Llongfile, log.Lshortfile, and log.LUTC.
package main
import "log"
func main() {
log.SetPrefix("INFO: ")
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.Println("This is a log message with custom prefix and flags")
} INFO: 2024/05/20 21:45:12 main.go:10: This is a log message with custom prefix and flagsAdvanced Usage
Beyond basic functions, you can create custom loggers and implement simple log level control.
Custom Logger
Use log.New() to create a logger with its own output, prefix, and flags.
package main
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("custom.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
defer file.Close()
customLogger := log.New(file, "CUSTOM: ", log.Ldate|log.Ltime|log.Lshortfile)
customLogger.Println("This is a message from the custom logger")
} cat ./custom.log
CUSTOM: 2024/05/20 21:45:49 main.go:16: This is a message from the custom loggerLog Level Management
The standard log package lacks built‑in levels, but you can wrap it to provide simple level filtering.
package main
import (
"log"
"os"
)
const (
LevelError = iota
LevelWarning
LevelInfo
)
var (
ErrorLogger *log.Logger
WarningLogger *log.Logger
InfoLogger *log.Logger
)
func init() {
file, err := os.OpenFile("leveled.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
ErrorLogger = log.New(file, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
WarningLogger = log.New(file, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile)
InfoLogger = log.New(file, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
}
func main() {
InfoLogger.Println("This is an info message")
WarningLogger.Println("This is a warning message")
ErrorLogger.Println("This is an error message")
} cat ./leveled.log
INFO: 2024/05/20 21:46:31 main.go:31: This is an info message
WARNING: 2024/05/20 21:46:31 main.go:32: This is a warning message
ERROR: 2024/05/20 21:46:31 main.go:33: This is an error messagePractical Tips
Log Level and Filtering: Direct different levels to separate files to avoid noise.
Unified Log Format: Agree on a common prefix and flag configuration across the team.
Performance Considerations: Avoid excessive logging in performance‑critical sections; use configurable switches.
Third‑Party Libraries: For richer features, consider logrus or zap.
Conclusion
The log package offers a straightforward yet powerful way to record runtime information in Go. Mastering its basic and advanced capabilities can greatly improve debugging efficiency, code maintainability, and overall software quality.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
