Where logs go
golog writes to any io.Writer. Each record is one Write call, under a lock that the handler shares with every
handler made from it by With and WithGroup, so lines from different goroutines never mix.
A file
Section titled “A file”Open the file yourself, handle the error, and hand it over. Leave Color off: escape codes in a file are noise.
f, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)if err != nil { return fmt.Errorf("open log: %w", err)}defer f.Close()
logger := slog.New(golog.NewHandler(f, nil))If a write fails, the handler’s Handle returns the error. *slog.Logger discards it, as it does for every handler;
to act on it, wrap the handler and check what Handle returns.
A terminal and a file at once
Section titled “A terminal and a file at once”slog.NewMultiHandler sends each record to several handlers, each with its own level and options.
This program logs Info and up to the terminal in colour, and everything to a file:
// Command file logs from one logger to two places: the terminal in colour, and a file in plain text with// Debug records too.//// go run ./examples/file app.logpackage main
import ( "fmt" "io" "log" "log/slog" "os"
"github.com/vardius/golog/v2")
// openLog opens path for appending, and creates it if it isn't there.func openLog(path string) (*os.File, error) { f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) if err != nil { return nil, fmt.Errorf("open log: %w", err) } return f, nil}
// newLogger logs Info and above to console in colour, and everything to file in plain text.func newLogger(console, file io.Writer) *slog.Logger { return slog.New(slog.NewMultiHandler( golog.NewHandler(console, &golog.Options{Color: true}), golog.NewHandler(file, &golog.Options{Level: slog.LevelDebug}), ))}
func run(path string, console io.Writer) error { f, err := openLog(path) if err != nil { return err } logger := newLogger(console, f)
logger.Debug("cache warmed", "entries", 1200) logger.Info("server started", "addr", ":8080")
return f.Close()}
func main() { log.SetFlags(0) if len(os.Args) != 2 { log.Fatal("usage: file <path>") } if err := run(os.Args[1], os.Stderr); err != nil { log.Fatal(err) }}JSON for machines
Section titled “JSON for machines”golog writes for people. Where a program reads the logs, such as a log collector, use slog’s JSON handler, alone or
next to golog’s with slog.NewMultiHandler:
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))This is also what replaces v1’s App Engine logger. If the platform that collects the logs asks for other field names,
for the level say, rename them with ReplaceAttr.
Values from a context
Section titled “Values from a context”slog hands the context passed to InfoContext and its siblings to the handler. golog’s handler doesn’t read it:
what to take from a context is up to the program. A small handler around golog’s can add it to each record.
This one adds the request ID that an HTTP middleware put in the request’s context:
// Command requestid serves HTTP and logs every request with an ID that its middleware puts in the request's// context. The logger finds it there: a handler wrapped around golog's reads it on every record.//// go run ./examples/requestid// curl localhost:8080/hellopackage main
import ( "context" "log" "log/slog" "net/http" "os" "strconv" "sync/atomic" "time"
"github.com/vardius/golog/v2")
type requestIDKey struct{}
// contextHandler adds the request ID in the context, if there is one, to each record it hands on.type contextHandler struct{ slog.Handler }
func (h contextHandler) Handle(ctx context.Context, r slog.Record) error { if id, ok := ctx.Value(requestIDKey{}).(string); ok { r.AddAttrs(slog.String("request_id", id)) } return h.Handler.Handle(ctx, r)}
func (h contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler { return contextHandler{h.Handler.WithAttrs(attrs)}}
func (h contextHandler) WithGroup(name string) slog.Handler { return contextHandler{h.Handler.WithGroup(name)}}
// withRequestID gives every request an ID in its context and logs it when it's served.func withRequestID(logger *slog.Logger, next http.Handler) http.Handler { var last atomic.Uint64 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() ctx := context.WithValue(r.Context(), requestIDKey{}, strconv.FormatUint(last.Add(1), 10)) next.ServeHTTP(w, r.WithContext(ctx)) logger.InfoContext(ctx, "served", "method", r.Method, "path", r.URL.Path, "took", time.Since(start)) })}
func newServer(logger *slog.Logger) http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) { logger.DebugContext(r.Context(), "saying hello") w.Write([]byte("hello\n")) }) return withRequestID(logger, mux)}
func main() { h := golog.NewHandler(os.Stderr, &golog.Options{Level: slog.LevelDebug}) logger := slog.New(contextHandler{h}) log.Fatal(http.ListenAndServe("localhost:8080", newServer(logger)))}2026-10-24T09:41:07.312+11:00 DEBUG saying hello request_id=12026-10-24T09:41:07.312+11:00 INFO served method=GET path=/hello took=61.2µs request_id=1