Step Over to Go Part 36 of 50
  1. 1 Goodbye .csproj, Hello go.mod
  2. 2 The Phrasebook: C# Concepts in Go Terms
  3. 3 You Know .NET, Now Meet the Go Toolchain
  4. 4 No Enums? No Problem (Sort Of)
  5. 5 Generics: Late to the Party
  6. 6 The Million Dollar Mistake, Differently
  7. 7 Your Class Is Now a Struct (And That's Fine)
  8. 8 Where Did My Properties Go?
  9. 9 if err != nil: Your New Reality
  10. 10 Panic and Recover: The Emergency Exit
  11. 11 The switch Statement You Always Wanted
  12. 12 Stack vs Heap: Go's Escape Analysis
  13. 13 Pointers Without the Pain
  14. 14 Slices Are Not Arrays (And Neither Is List<T>)
  15. 15 Channels: The sync You Didn't Know You Wanted
  16. 16 Context Is King
  17. 17 Async/Await vs Goroutines: A Mindset Shift
  18. 18 select: Multiplexing Like a Pro
  19. 19 Mutexes and WaitGroups: When Channels Aren't the Answer
  20. 20 The Empty Interface and Type Assertions
  21. 21 Composition Over Inheritance (For Real This Time)
  22. 22 Implicit Interfaces: Scary Then Brilliant
  23. 23 Benchmarks and Profiling Out of the Box
  24. 24 Mocking in a Language Without Mockito
  25. 25 Multi-Module Repos: Monorepo Thinking
  26. 26 Organising a Real Project
  27. 27 Testing Without a Framework
  28. 28 Configuration Without IOptions<T>
  29. 29 Database Access: database/sql vs Entity Framework
  30. 30 Debugging: Delve vs Visual Studio's Comfort
  31. 31 Generate All the Things
  32. 32 GORM and Friends: When You Do Want an ORM
  33. 33 HTTP Services: net/http vs ASP.NET Core
  34. 34 JSON: Struct Tags and the Marshal Dance
  35. 35 Linting and Formatting: gofmt Is Non-Negotiable
  36. 36 Logging: slog and the Structured Logging Story
  37. 37 Shrinking Binaries and Build Tags
  38. 38 Dockerfile for Go: Simpler Than You'd Think
  39. 39 GitHub Actions for Go Projects
  40. 40 Health Checks and Readiness Probes
  41. 41 Kubernetes and Go: A Natural Fit
  42. 42 AWS Lambda and Go: Cold Starts That Don't Hurt
  43. 43 Metrics, Traces, and Logs: The OpenTelemetry Way
  44. 44 Single Binary Deploys: The Killer Feature
  45. 45 Versioning Your Modules
  46. 46 What I Actually Miss From C#
  47. 47 What I'll Never Go Back For
  48. 48 Six Months In: Was It Worth It?
  49. 49 Forty-Eight Posts on Moving From C# to Go, in the Right Order
  50. 50 Range-Over-Func Iterators for People Who Miss LINQ
About this series

Logging: slog and the Structured Logging Story

For years, Go's logging story was “use the log package or pick a third-party library.” The standard log package is basic: no levels, no structure, no context. Everyone used zerolog, zap, or logrus.

Then Go 1.21 shipped log/slog. Finally, structured logging in the standard library. And it's actually good.

The Old Way: log Package

Go's original log package:

import "log"

log.Println("server starting")
log.Printf("listening on port %d", 8080)
log.Fatal("failed to connect")  // logs and calls os.Exit(1)

Output:

2025/01/04 10:30:00 server starting
2025/01/04 10:30:00 listening on port 8080

No levels. No structure. Just text. Fine for simple programs, inadequate for production.

The New Way: slog

Go 1.21's log/slog package:

import "log/slog"

slog.Info("server starting")
slog.Info("listening", "port", 8080)
slog.Error("failed to connect", "error", err, "host", hostname)

Default text output:

2025/01/04 10:30:00 INFO server starting
2025/01/04 10:30:00 INFO listening port=8080
2025/01/04 10:30:00 ERROR failed to connect error="connection refused" host="db.example.com"

Or JSON:

logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
slog.SetDefault(logger)
{"time":"2025-01-04T10:30:00Z","level":"INFO","msg":"listening","port":8080}

Log Levels

slog has four levels:

slog.Debug("detailed debugging info")
slog.Info("normal operation")
slog.Warn("something unexpected")
slog.Error("something failed")

Set the minimum level:

opts := &slog.HandlerOptions{
    Level: slog.LevelDebug,  // show Debug and above
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))

Structured Attributes

Add key-value pairs to log entries:

// Alternating key-value pairs
slog.Info("user created", "user_id", userID, "email", email)

// Or use slog.Attr for type safety
slog.Info("user created",
    slog.Int("user_id", userID),
    slog.String("email", email),
    slog.Time("created_at", time.Now()),
)

Logger with Context

Add attributes that appear in every log entry:

logger := slog.Default().With(
    "service", "user-api",
    "version", "1.2.3",
)

logger.Info("request received")
// {"time":"...","level":"INFO","msg":"request received","service":"user-api","version":"1.2.3"}

Or create child loggers:

func handleRequest(r *http.Request) {
    requestID := r.Header.Get("X-Request-ID")
    log := slog.Default().With("request_id", requestID)
    
    log.Info("processing request")
    // ... later
    log.Info("request complete")  // both have request_id
}

Comparing to ILogger

C#'s ILogger:

_logger.LogInformation("User created: {UserId} {Email}", userId, email);

Go's slog:

slog.Info("user created", "user_id", userID, "email", email)

Similar structured logging. Different syntax.

Feature ILogger slog
Structured logging Yes Yes
Log levels 6 (Trace-Critical) 4 (Debug-Error)
Scopes BeginScope() With()
DI integration Built-in Manual
Providers Many built-in Handlers (fewer)
Message templates {Named} placeholders Key-value pairs
Log categories Type-based Manual grouping

Using slog with HTTP Context

Pass loggers through context:

type ctxKey struct{}

func WithLogger(ctx context.Context, logger *slog.Logger) context.Context {
    return context.WithValue(ctx, ctxKey{}, logger)
}

func FromContext(ctx context.Context) *slog.Logger {
    if logger, ok := ctx.Value(ctxKey{}).(*slog.Logger); ok {
        return logger
    }
    return slog.Default()
}

Middleware to add request context:

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        logger := slog.Default().With(
            "request_id", r.Header.Get("X-Request-ID"),
            "method", r.Method,
            "path", r.URL.Path,
        )
        
        ctx := WithLogger(r.Context(), logger)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

// In handlers
func handler(w http.ResponseWriter, r *http.Request) {
    log := FromContext(r.Context())
    log.Info("processing")  // includes request context
}

Custom Handlers

slog uses handlers for output. Write your own:

type PrettyHandler struct {
    slog.Handler
    w io.Writer
}

func (h *PrettyHandler) Handle(ctx context.Context, r slog.Record) error {
    // Custom formatting
    fmt.Fprintf(h.w, "[%s] %s: %s\n",
        r.Time.Format("15:04:05"),
        r.Level,
        r.Message,
    )
    r.Attrs(func(a slog.Attr) bool {
        fmt.Fprintf(h.w, "  %s=%v\n", a.Key, a.Value)
        return true
    })
    return nil
}

Or wrap existing handlers for filtering, sampling, etc.

Third-Party Integration

slog plays well with existing libraries:

Output to zerolog:

// zerolog adapter available

Output to zap:

// zapslog adapter available

You can use slog's API with your preferred backend.

Performance Considerations

slog is designed for production:

// Avoid allocation if level disabled
if slog.Default().Enabled(ctx, slog.LevelDebug) {
    slog.Debug("expensive operation", "data", expensiveComputation())
}

Or use LogAttrs for zero-allocation logging:

slog.Default().LogAttrs(ctx, slog.LevelInfo, "event",
    slog.String("key", value),
    slog.Int("count", n),
)

The Honest Take

slog is a welcome addition. Not as mature as the third-party options, but good enough for most uses.

What slog does well:

  • Standard library (no dependencies)
  • Good API design
  • Structured by default
  • Handler abstraction for extensibility

What ILogger does better:

  • More log levels
  • Richer ecosystem
  • DI integration
  • Better provider options (Application Insights, Seq, etc.)
  • Message templates with semantic meaning

What third-party Go loggers do better:

  • zerolog: extremely fast, zero allocation
  • zap: battle-tested, rich features
  • Both: more production-proven

The verdict: For new projects, slog is a solid choice. It's in the standard library, it's structured, it works.

For high-performance logging or specific output requirements, zerolog or zap might still be better.

If you're coming from ILogger, you'll find slog familiar but simpler. Fewer features, but the core functionality is there.


Next up: database access with database/sql. Raw SQL, connection pooling, and missing your ORM.