Logging
Logging in Go is typically done using the built-in log
package or other third-party logging libraries for more advanced features.
Normal Logging
package main
import "log"
func main() {
// Basic logging
log.Println("This is a basic log message")
// Logging with formatting
name := "John"
age := 30
log.Printf("Name: %s, Age: %d", name, age)
// Setting log prefix
log.SetPrefix("[MyApp] ")
log.Println("Log message with custom prefix")
// Setting log flags
log.SetFlags(log.Ldate | log.Ltime)
log.Println("Log message with custom date and time format")
}
Its output:
2013/10/07 09:42:00 This is a basic log message
2013/10/07 09:42:00 Name: John, Age: 30
[MyApp] 2013/10/07 09:42:00 Log message with custom prefix
[MyApp] 2013/10/07 09:42:00 Log message with custom date and time format
Structured Logging
Package slog
provides structured logging, in which log records include a message, a severity level, and various other attributes expressed as key-value pairs.
package main
import (
"log/slog"
"os"
)
func main() {
jsonHandler := slog.NewJSONHandler(os.Stdout, nil)
myslog := slog.New(jsonHandler)
myslog.Info("hi there")
myslog.Info("hello again", "key", "val", "age", 25)
}
Its output:
{"time":"2009-11-10T23:00:00Z","level":"INFO","msg":"hi there"}
{"time":"2009-11-10T23:00:00Z","level":"INFO","msg":"hello again","key":"val","age":25}
Loading...
> code result goes here