Logging
package main
import (
"bytes"
"fmt"
"log"
"os"
"log/slog"
)
func main() {
// Standard logger usage
log.Println("standard logger")
// Modify standard logger flags to include microseconds
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
log.Println("with micro")
// Modify standard logger flags to include file and line
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.Println("with file/line")
// Creating a custom logger (mylog) with a prefix and specific flags
mylog := log.New(os.Stdout, "my:", log.LstdFlags)
mylog.Println("from mylog")
// Changing prefix for the custom logger
mylog.SetPrefix("ohmy:")
mylog.Println("from mylog")
// Creating a logger (buflog) that writes to a buffer
var buf bytes.Buffer
buflog := log.New(&buf, "buf:", log.LstdFlags)
buflog.Println("hello")
// Printing the content of the buffer
fmt.Print("from buflog:", buf.String())
// Using the slog package to create a structured logger (myslog)
jsonHandler := slog.NewJSONHandler(os.Stderr, nil)
myslog := slog.New(jsonHandler)
// Logging messages with additional key-value pairs
myslog.Info("hi there")
myslog.Info("hello again", "key", "val", "age", 25)
}Output
Last updated