Frameworks 10 min read

Go slog: structured logging with log/slog

How to use slog, the Go (Golang) standard structured logging package log/slog, in a real service: handlers and levels, typed attributes, request-scoped loggers, trace IDs on every line, and shipping the same records over OTLP. Tested with Go 1.26 and OpenTelemetry Go 1.47 (November 2026).

David Granzin By David Granzin

slog is the structured logging package in Go's standard library (log/slog, Go 1.21+). Each call produces a record with a time, a level, a message and key-value attributes, and a handler decides how it is written.

The smallest useful setup is one line in main. There is nothing to install and no environment variable to set.

main.go

package main

import (
	"log/slog"
	"os"
)

func main() {
	// JSON to stdout, used by every slog.Info/Error call in the program.
	slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))

	slog.Info("server started", "port", 8080)
	slog.Error("charge failed", "order_id", 4182, "error", "card declined")
}
$ go run .
{"time":"2026-11-29T01:51:18.639978+01:00","level":"INFO","msg":"server started","port":8080}
{"time":"2026-11-29T01:51:18.640217+01:00","level":"ERROR","msg":"charge failed","order_id":4182,"error":"card declined"}

Key takeaways

  • Use JSONHandler in production and TextHandler on your machine. Call slog.SetDefault once at startup.
  • The default level is Info. Set HandlerOptions.Level to a LevelVar to change it without a restart.
  • Prefer typed attrs and LogAttrs on hot paths. Loose pairs are where !BADKEY comes from.
  • Trace IDs only reach a log line if you call InfoContext with the request's context.

slog basics: TextHandler, JSONHandler and SetDefault

This section covers the two built-in handlers and the options they share. TextHandler writes key=value lines for a terminal, and JSONHandler writes one JSON object per line for everything else.

main.go

package main

import (
	"log/slog"
	"os"
)

func main() {
	// Human-readable key=value lines, good for a terminal.
	text := slog.New(slog.NewTextHandler(os.Stdout, nil))
	text.Info("order placed", "order_id", 4182, "total", 59.90)

	// One JSON object per line, what log pipelines expect.
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	logger.Info("order placed", "order_id", 4182, "total", 59.90)

	// Make it the logger behind slog.Info, slog.Error and the old log package.
	slog.SetDefault(logger)
	slog.Warn("stock low", "sku", "TSHIRT-M", "left", 3)
}
time=2026-11-29T01:24:22.831+01:00 level=INFO msg="order placed" order_id=4182 total=59.9
{"time":"2026-11-29T01:24:22.83197+01:00","level":"INFO","msg":"order placed","order_id":4182,"total":59.9}
{"time":"2026-11-29T01:24:22.832015+01:00","level":"WARN","msg":"stock low","sku":"TSHIRT-M","left":3}

slog.SetDefault does two things, so call it once in main before anything logs:

  • The package-level functions (slog.Info, slog.Error) start using your logger.
  • So does the old log package: a dependency's log.Printf comes out through your handler at Info level.

Levels and LevelVar

slog has four named levels. They are integers with gaps between them, so you can define your own, such as slog.Level(-8) for trace.

LevelValuePrinted as
slog.LevelDebug-4DEBUG
slog.LevelInfo0INFO
slog.LevelWarn4WARN
slog.LevelError8ERROR
slog.Level(2)2INFO+2

A handler drops everything below its minimum level, which is Info by default. Set HandlerOptions.Level to a fixed level, or to a *slog.LevelVar to change it while the process runs:

// A LevelVar is a level you can change while the program runs.
level := new(slog.LevelVar) // zero value is Info
if err := level.UnmarshalText([]byte(os.Getenv("LOG_LEVEL"))); err != nil {
	level.Set(slog.LevelInfo)
}

logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))

logger.Debug("cache miss", "key", "user:42") // dropped at Info
level.Set(slog.LevelDebug)                   // e.g. from a signal or admin endpoint
logger.Debug("cache miss", "key", "user:42") // printed
  • UnmarshalText accepts DEBUG, INFO, WARN and ERROR in any case, plus offsets such as INFO+2. An empty or unknown string is an error.
  • LevelVar is safe for concurrent use. A signal handler or an admin endpoint can call Set at any time.

AddSource and ReplaceAttr

AddSource adds the function, file and line of the log call. ReplaceAttr is called for every attribute before it is written, including the built-in time, level, msg and source. Use it to rename keys or blank out secrets.

var secretKeys = map[string]bool{"password": true, "token": true, "authorization": true}

func replace(groups []string, a slog.Attr) slog.Attr {
	// Built-in keys only exist at the top level, outside any group.
	if len(groups) == 0 {
		switch a.Key {
		case slog.TimeKey:
			a.Key = "ts"
		case slog.MessageKey:
			a.Key = "message"
		case slog.SourceKey:
			// Shorten /home/ci/app/main.go to main.go.
			if src, ok := a.Value.Any().(*slog.Source); ok {
				src.File = filepath.Base(src.File)
			}
		}
	}
	if secretKeys[a.Key] {
		a.Value = slog.StringValue("[REDACTED]")
	}
	return a
}

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		AddSource:   true,
		ReplaceAttr: replace,
	}))
	logger.Info("login", "user", "ada", "password", "hunter2")
}
{"ts":"2026-11-29T01:24:23.56605+01:00","level":"INFO","source":{"function":"main.main","file":"main.go","line":37},"message":"login","user":"ada","password":"[REDACTED]"}
  • Keep it cheap. It runs on every attribute of every record: a map lookup, not a regular expression.
  • Check groups. The built-in keys only appear when it is empty.
  • Return a zero slog.Attr{} to drop an attribute, such as time when the platform already adds a timestamp.
  • AddSource costs a runtime.Callers call per record, which is measurable only on a very hot path.

Attrs, key-value pairs and the LogAttrs fast path

There are three ways to attach data to a log line. They print the same output and differ in safety and cost.

// Loose pairs: short, but nothing checks that keys and values line up.
logger.Info("payment captured", "amount", 59.90, "currency", "EUR")

// Attrs: typed, checked by the compiler, and they can be mixed with pairs.
logger.Info("payment captured", slog.Float64("amount", 59.90), slog.String("currency", "EUR"))

// LogAttrs: attrs only, no allocations for the arguments. Use it on hot paths.
logger.LogAttrs(ctx, slog.LevelInfo, "payment captured",
	slog.Float64("amount", 59.90),
	slog.String("currency", "EUR"),
	slog.Duration("took", 41*time.Millisecond),
	slog.Group("card", slog.String("brand", "visa"), slog.String("last4", "4242")),
)
{"time":"...","level":"INFO","msg":"payment captured","amount":59.9,"currency":"EUR","took":41000000,"card":{"brand":"visa","last4":"4242"}}
StyleChecked at compile timeCost
Loose pairs, "key", valueNo. Mistakes print !BADKEY.Each value is boxed into an interface
Attrs, slog.String(...)YesStill passed as ...any
LogAttrsYes, attrs onlyNo boxing. The first five attrs do not allocate.

Use LogAttrs in middleware and in loops. For an error, the convention is slog.Any("error", err), which prints err.Error() and no stack trace.

A type controls how it is logged by implementing slog.LogValuer. This is the safest place to redact, because it does not depend on the key name:

// Token never prints its value, whichever handler formats it.
type Token string

func (Token) LogValue() slog.Value { return slog.StringValue("[REDACTED]") }

logger.Info("session created", "token", Token("sk_live_abc123"))
// {"time":"...","level":"INFO","msg":"session created","token":"[REDACTED]"}

With and WithGroup

With and WithGroup derive a logger that carries fields for you: one per service at startup, one per request when you want an ID on every line. With adds attributes to every record. WithGroup nests everything added afterwards under a name.

base := slog.New(slog.NewJSONHandler(os.Stdout, nil)).
	With("service", "checkout", "version", "1.4.2")

// With: these attrs are on every line this logger writes.
reqLog := base.With("request_id", "req_8f3a")
reqLog.Info("cart loaded", "items", 3)

// WithGroup: everything added after it is nested under "db".
dbLog := reqLog.WithGroup("db")
dbLog.Info("query done", "table", "orders", "rows", 12)
{"time":"...","level":"INFO","msg":"cart loaded","service":"checkout","version":"1.4.2","request_id":"req_8f3a","items":3}
{"time":"...","level":"INFO","msg":"query done","service":"checkout","version":"1.4.2","request_id":"req_8f3a","db":{"table":"orders","rows":12}}
  • With is cheaper than repeating pairs. Its attributes are formatted once, when With is called, and reused.
  • Order matters with WithGroup. Attributes added before it stay at the top level. Everything after it goes inside the group.
  • Keep request-wide fields at the top level, where they are easy to filter on.

Context-aware logging and trace IDs

This section puts the OpenTelemetry trace ID on every log line, so you can go from one error log to the whole request. Every level has a context variant (InfoContext, ErrorContext) that hands the context to the handler's Handle method.

The built-in handlers ignore that context, so the variants only do something when a handler you install reads it.

A handler that reads the active span is about twenty lines:

main.go

package main

import (
	"context"
	"log/slog"
	"os"

	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/trace"
)

// TraceHandler wraps any slog.Handler and adds the IDs of the span in ctx.
type TraceHandler struct{ slog.Handler }

func (h TraceHandler) Handle(ctx context.Context, r slog.Record) error {
	if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
		r.AddAttrs(
			slog.String("trace_id", sc.TraceID().String()),
			slog.String("span_id", sc.SpanID().String()),
		)
	}
	return h.Handler.Handle(ctx, r)
}

// Without these two, logger.With(...) would return the inner handler
// and the trace IDs would silently disappear.
func (h TraceHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
	return TraceHandler{h.Handler.WithAttrs(attrs)}
}

func (h TraceHandler) WithGroup(name string) slog.Handler {
	return TraceHandler{h.Handler.WithGroup(name)}
}

func main() {
	logger := slog.New(TraceHandler{slog.NewJSONHandler(os.Stdout, nil)})

	tp := sdktrace.NewTracerProvider()
	defer tp.Shutdown(context.Background())
	ctx, span := tp.Tracer("checkout").Start(context.Background(), "charge card")
	defer span.End()

	logger.InfoContext(ctx, "card charged", "amount", 59.90) // has trace_id
	logger.Info("card charged", "amount", 59.90)             // no ctx, no trace_id
}
{"time":"...","level":"INFO","msg":"card charged","amount":59.9,"trace_id":"79b578e2fce5123d951cebdcb8962874","span_id":"f00ba1c680e8af28"}
{"time":"...","level":"INFO","msg":"card charged","amount":59.9}
  • Write WithAttrs and WithGroup by hand. The embedded versions return the inner handler, so your wrapper is gone after the first logger.With.
  • Groups capture the IDs. A logger made with WithGroup("db") writes trace_id inside the db object, because AddAttrs adds to the open group. The bridge in the next section stores the IDs outside the attributes.
  • Something has to start the span. See context propagation for how the trace reaches your service.

The otelslog bridge: slog records over OTLP

This section sends the same records straight from the process over OTLP, next to the JSON on stdout. The otelslog bridge is a slog.Handler that turns each slog record into an OpenTelemetry log record. Your logging calls do not change.

go get go.opentelemetry.io/contrib/bridges/otelslog \
  go.opentelemetry.io/contrib/processors/minsev \
  go.opentelemetry.io/otel/sdk/log \
  go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp

main.go

package main

import (
	"context"
	"log/slog"
	"os"
	"os/signal"
	"syscall"

	"go.opentelemetry.io/contrib/bridges/otelslog"
	"go.opentelemetry.io/contrib/processors/minsev"
	"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
	"go.opentelemetry.io/otel/log/global"
	sdklog "go.opentelemetry.io/otel/sdk/log"
	"go.opentelemetry.io/otel/sdk/resource"
	semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
)

func main() {
	// Cancelled on Ctrl-C or SIGTERM, so the deferred Shutdown below runs.
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	// Endpoint and headers come from OTEL_EXPORTER_OTLP_* variables.
	exporter, err := otlploghttp.New(ctx)
	if err != nil {
		panic(err)
	}

	// Later options win: the code sets defaults, the environment overrides them.
	res, err := resource.New(ctx,
		resource.WithAttributes(
			semconv.ServiceName("checkout"),
			semconv.DeploymentEnvironmentName("production"),
		),
		resource.WithFromEnv(), // OTEL_SERVICE_NAME, OTEL_RESOURCE_ATTRIBUTES
	)
	if err != nil {
		panic(err)
	}

	// The bridge has no level of its own: drop Debug before it is batched.
	processor := minsev.NewLogProcessor(sdklog.NewBatchProcessor(exporter), minsev.SeverityInfo)

	provider := sdklog.NewLoggerProvider(
		sdklog.WithResource(res),
		sdklog.WithProcessor(processor),
	)
	// Flush the last batch. ctx is cancelled by then, so use a fresh one.
	defer provider.Shutdown(context.Background())
	global.SetLoggerProvider(provider)

	// Every record goes to stdout as JSON and to the OTLP endpoint.
	// NewMultiHandler needs Go 1.26. On older versions use fanout{...} below.
	logger := slog.New(slog.NewMultiHandler(
		slog.NewJSONHandler(os.Stdout, nil),
		otelslog.NewHandler("checkout", otelslog.WithLoggerProvider(provider)),
	))
	slog.SetDefault(logger)

	slog.DebugContext(ctx, "dropped by both handlers")
	slog.InfoContext(ctx, "card charged", "amount", 59.90, slog.Group("card", "brand", "visa"))

	// In a server: run it here and return when ctx is done.
	// <-ctx.Done()
}
PartWhat to know
ExporterOTLP over HTTP. With no options it reads OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_EXPORTER_OTLP_HEADERS. Use otlploggrpc for gRPC.
ResourceLater options win. WithFromEnv comes last, so OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES override the values in code, which are the fallback.
Batch processorExports every second or at 512 records. provider.Shutdown flushes the queue.
minsevThe minimum severity for export. The bridge ignores HandlerOptions.Level, so without it every Debug record is exported even though stdout hides it.
NewMultiHandlerSends each record to both handlers. Added in Go 1.26.

The last batch on SIGTERM

Go's default reaction to SIGTERM is to exit at once, without running deferred calls, so the queued records are lost. signal.NotifyContext turns the signal into a cancelled context. main then returns normally and the deferred Shutdown exports what is left.

On Go 1.21 to 1.25, this handler does the job of NewMultiHandler. Add it to the file and swap the one call:

// fanout sends each record to every handler. It needs the "errors" import.
type fanout []slog.Handler

func (f fanout) Enabled(ctx context.Context, l slog.Level) bool {
	for _, h := range f {
		if h.Enabled(ctx, l) {
			return true
		}
	}
	return false
}

func (f fanout) Handle(ctx context.Context, r slog.Record) error {
	var errs []error
	for _, h := range f {
		if h.Enabled(ctx, r.Level) {
			errs = append(errs, h.Handle(ctx, r.Clone()))
		}
	}
	return errors.Join(errs...)
}

func (f fanout) WithAttrs(attrs []slog.Attr) slog.Handler {
	out := make(fanout, len(f))
	for i, h := range f {
		out[i] = h.WithAttrs(attrs)
	}
	return out
}

func (f fanout) WithGroup(name string) slog.Handler {
	out := make(fanout, len(f))
	for i, h := range f {
		out[i] = h.WithGroup(name)
	}
	return out
}

// In main, before Go 1.26:
// logger := slog.New(fanout{
// 	slog.NewJSONHandler(os.Stdout, nil),
// 	otelslog.NewHandler("checkout", otelslog.WithLoggerProvider(provider)),
// })

Run it with OTEL_EXPORTER_OTLP_ENDPOINT pointing at any OTLP endpoint, such as a local Collector. This is the request the endpoint received, decoded to JSON and trimmed:

{
  "resource": {
    "attributes": [
      { "key": "deployment.environment.name", "value": { "stringValue": "production" } },
      { "key": "service.name", "value": { "stringValue": "checkout" } }
    ]
  },
  "scopeLogs": [{
    "scope": { "name": "checkout" },
    "logRecords": [{
      "timeUnixNano": "1795911904344026000",
      "severityNumber": "SEVERITY_NUMBER_INFO",
      "severityText": "INFO",
      "body": { "stringValue": "card charged" },
      "attributes": [
        { "key": "amount", "value": { "doubleValue": 59.9 } },
        { "key": "card", "value": { "kvlistValue": { "values": [
          { "key": "brand", "value": { "stringValue": "visa" } }
        ] } } }
      ],
      "traceId": "fZTqk6Z8g5naB3qEHWQxfg==",
      "spanId": "RHEGGMVozGY="
    }]
  }]
}
  • The message became the body, the level became the severity, attributes kept their types, and the slog group became a nested key-value list.
  • The trace and span IDs are fields of the record itself. This capture was made inside a span; records logged without one have no IDs. They are base64 only because of how protobuf prints bytes as JSON.

As of November 2026 the logs SDK follows the main OpenTelemetry Go version (v1.47), while the bridge (v0.21), the OTLP log exporter (v0.23) and minsev (v0.17) are still v0.x. Sampling a trace out does not remove its logs.

HTTP request logging middleware

This middleware writes one line per request with the method, route, status and duration. net/http does not expose the status a handler wrote, so it wraps the ResponseWriter to record it.

main.go

// statusRecorder remembers what the handler wrote.
type statusRecorder struct {
	http.ResponseWriter
	status int
	bytes  int
}

func (w *statusRecorder) WriteHeader(code int) {
	w.status = code
	w.ResponseWriter.WriteHeader(code)
}

func (w *statusRecorder) Write(b []byte) (int, error) {
	n, err := w.ResponseWriter.Write(b)
	w.bytes += n
	return n, err
}

// Unwrap lets http.ResponseController reach Flush, Hijack and friends.
func (w *statusRecorder) Unwrap() http.ResponseWriter { return w.ResponseWriter }

func RequestLogger(logger *slog.Logger, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}

		next.ServeHTTP(rec, r)

		level := slog.LevelInfo
		if rec.status >= 500 {
			level = slog.LevelError
		}
		// r.Pattern is the matched route, e.g. "GET /orders/{id}" (Go 1.23+).
		logger.LogAttrs(r.Context(), level, "http request",
			slog.String("method", r.Method),
			slog.String("route", r.Pattern),
			slog.String("path", r.URL.Path),
			slog.Int("status", rec.status),
			slog.Int("bytes", rec.bytes),
			slog.Duration("duration", time.Since(start)),
		)
	})
}

func main() {
	logger := slog.New(TraceHandler{slog.NewJSONHandler(os.Stdout, nil)})
	otel.SetTracerProvider(sdktrace.NewTracerProvider())

	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
		// Pass the request context so this line joins the same trace.
		logger.InfoContext(r.Context(), "order loaded", "order_id", r.PathValue("id"))
		w.Write([]byte("ok\n"))
	})
	mux.HandleFunc("GET /boom", func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "boom", http.StatusInternalServerError)
	})

	// otelhttp is outermost: it starts the span the logger then reads from ctx.
	handler := otelhttp.NewHandler(RequestLogger(logger, mux), "http.server")
	http.ListenAndServe(":8080", handler)
}
{"time":"...","level":"INFO","msg":"order loaded","order_id":"4182","trace_id":"6da77566e736a4348e78e91069469def","span_id":"37ec1c1771f08014"}
{"time":"...","level":"INFO","msg":"http request","method":"GET","route":"GET /orders/{id}","path":"/orders/4182","status":200,"bytes":3,"duration":250875,"trace_id":"6da77566e736a4348e78e91069469def","span_id":"37ec1c1771f08014"}
{"time":"...","level":"ERROR","msg":"http request","method":"GET","route":"GET /boom","path":"/boom","status":500,"bytes":5,"duration":5625,"trace_id":"252ab27fd79aefe1cc53bb515198d4d1","span_id":"b2bbe714e8e110fb"}
  • Log the route, not only the path. r.Pattern gives GET /orders/{id}, which you can group and count. It is empty when no route matched, as on a 404.
  • Order the middleware. The logger must run inside otelhttp.NewHandler. Swap the two and the request line has no trace ID.
  • Use r.Context() in handlers. That is the only reason "order loaded" shares a trace_id with its request line.
  • Keep Unwrap. Without it, the wrapped writer hides http.Flusher and breaks streaming responses and server-sent events.
  • Do not log headers or bodies by default. They hold tokens and personal data.

Testing log output

A handler writes to any io.Writer, so code that takes a *slog.Logger as a dependency is easy to test. Point a JSON handler at a bytes.Buffer, run the code, and decode what it wrote:

order_test.go

package order

import (
	"bytes"
	"context"
	"encoding/json"
	"log/slog"
	"testing"
)

func TestPlaceLogsOrderID(t *testing.T) {
	var buf bytes.Buffer
	svc := Service{Log: slog.New(slog.NewJSONHandler(&buf, nil))}

	svc.Place(context.Background(), 4182)

	var line map[string]any
	if err := json.Unmarshal(buf.Bytes(), &line); err != nil {
		t.Fatalf("not one JSON line: %v\n%s", err, buf.String())
	}
	// JSON numbers decode to float64.
	if line["msg"] != "order placed" || line["order_id"] != float64(4182) {
		t.Errorf("unexpected log line: %v", line)
	}
}
  • Assert on the fields you care about, not the whole line. The time value changes on every run.
  • Code that calls the package-level slog.Info is harder to test: the test has to swap the global with slog.SetDefault and cannot run in parallel.

When a test does not care about logs, pass a logger that throws everything away:

// Go 1.24+
svc := Service{Log: slog.New(slog.DiscardHandler)}

// Before Go 1.24
svc := Service{Log: slog.New(slog.NewTextHandler(io.Discard, nil))}

slog vs zap vs zerolog

All three write structured JSON and all three are fine choices. This table shows where they differ.

slogzapzerolog
Where it livesStandard library, Go 1.21+go.uber.org/zapgithub.com/rs/zerolog
API stylePairs or typed attrsTyped fields, plus a looser SugaredLoggerChained calls ending in .Msg()
SpeedFast with LogAttrs, usually behind the other twoVery fastVery fast, often the fewest allocations
ExtrasFew: no sampling, no rotationSampling, stack traces, level hooksSampling, hooks, pretty console writer
  • Choose slog for new code. It has no dependencies and it is the interface other libraries accept, so you end up with one logger and not three.
  • Choose zap or zerolog when you have measured that logging costs you at high volume, or when you depend on a feature such as zap's built-in sampling.
  • Already on one of them? There is little to gain from a rewrite. zap ships a slog handler (go.uber.org/zap/exp/zapslog), so application code can call slog while zap does the encoding.

Common problems and fixes

These are the slog problems people search for most, each with its cause and fix.

Debug lines are not printing

The minimum level is Info, for the default logger and for any handler created with nil options. Check in order:

  • The handler has no level set. Pass &slog.HandlerOptions{Level: slog.LevelDebug}, or a LevelVar.
  • You are using the built-in default logger. Call slog.SetLogLoggerLevel(slog.LevelDebug) (Go 1.22+).
  • A different logger is in use. slog.SetDefault only affects slog.Debug and friends. A *slog.Logger stored in a struct keeps its own handler and level.
  • The level variable was never read. A LOG_LEVEL set in your shell is not set in the container.

!BADKEY in the output

slog reads the arguments after the message as key, value, key, value. When that pattern breaks, it writes the stray value under the key !BADKEY:

logger.Info("user loaded", userID)                    // a value with no key
logger.Info("user loaded", "user_id", userID, "plan") // a key with no value
{"time":"...","level":"INFO","msg":"user loaded","!BADKEY":42}
{"time":"...","level":"INFO","msg":"user loaded","user_id":42,"!BADKEY":"plan"}

The usual causes are a forgotten key, an odd number of arguments, or an error passed on its own, as in logger.Error("failed", err). go vet catches these, and it runs as part of go test:

$ go vet ./...
main.go:11:29: slog.Logger.Info arg "userID" should be a string or a slog.Attr (possible missing key or value)
main.go:12:2: call to slog.Logger.Info missing a final value

Typed attrs make the mistake impossible to write. The sloglint linter can require them.

Logs are missing trace IDs

The handler can only read the span from the context it is given. Work through these:

  1. The call has no context. logger.Info(...) passes context.Background(). Use logger.InfoContext(ctx, ...).
  2. The context is the wrong one. A function that builds its own context.Background() cuts the chain. Pass ctx down from r.Context().
  3. No span was started. Without otelhttp or another instrumentation around the handler, the context has no span.
  4. A goroutine outlived the request. Work started with go must receive the context as an argument. Use context.WithoutCancel(ctx) to keep the trace without being cancelled with the request.
  5. The wrapper was dropped. A custom handler without its own WithAttrs and WithGroup stops adding IDs after the first logger.With.

Durations print as huge numbers

JSONHandler writes a time.Duration as integer nanoseconds, so 41 ms is 41000000. TextHandler writes 41ms. A dashboard that expects milliseconds is off by a factor of a million. Pick a unit and put it in the key, such as slog.Float64("duration_ms", ...), or convert every duration in ReplaceAttr by checking a.Value.Kind() == slog.KindDuration.

Send it to Maple

The bridge setup above needs only an endpoint and a key. Logs that carry a trace ID are linked to their trace.

export OTEL_SERVICE_NAME="checkout"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.maple.dev"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_INGEST_KEY"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"

In Go the transport is chosen by the exporter package (otlploghttp here, otlploggrpc for gRPC), so the protocol line records that choice and does not switch it. The Maple Go instrumentation guide has the full setup for traces, metrics and logs.

The Logs page in Maple filtered to WARN: a list of payment-svc log lines reading pool exhausted, with severity and service filters beside the list.
slog records in Maple, filtered by the severity and service.name the bridge sends.

Sources and further reading

FAQ

よくある質問

What is slog in Golang?
slog is the structured logging package in Go's standard library, imported as log/slog and available since Go 1.21. A Logger turns each call into a Record with a time, level, message and key-value attributes, and a Handler writes it out. The standard library ships a TextHandler for key=value lines and a JSONHandler for one JSON object per line.
Why are my slog.Debug messages not printing?
The default minimum level is Info, so Debug records are dropped. Pass &slog.HandlerOptions{Level: slog.LevelDebug} when you create the handler, or call slog.SetLogLoggerLevel(slog.LevelDebug) if you use the default logger without your own handler.
What does !BADKEY mean in slog output?
slog expects alternating keys and values after the message. !BADKEY is the key it invents when a value has no string key in front of it, or when the last key has no value. Fix the argument list, or use typed attrs such as slog.String and slog.Int. go vet reports both mistakes.
How do I change the slog level at runtime?
Use a slog.LevelVar as the Level in HandlerOptions and call its Set method later, for example from a signal handler or an admin endpoint. The handler reads the variable on every log call, and LevelVar is safe to use from several goroutines.
How do I add a trace ID to slog logs?
Log with the context methods (InfoContext, ErrorContext, LogAttrs) and pass the request's context. Then either wrap your handler in a small one that reads trace.SpanContextFromContext(ctx) and adds trace_id and span_id, or use the otelslog bridge, which sets the trace and span ID on each OpenTelemetry log record.
Is slog faster than zap or zerolog?
No. zerolog and zap are usually faster and allocate less in benchmarks, because their APIs are built around avoiding allocations. slog with LogAttrs is close enough for most services, has no dependencies, and is the interface other libraries accept. You can also keep the slog API and use zap as the backend through its slog handler.

今日、最初のトレースを。

SDKを追加し、OTLPエクスポーターをMapleに向ければトレースが届きます。

maple.dev:OpenTelemetryの上のオブザーバビリティ