go
29 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package observability
import (
"context"
"log/slog"
"os"
)
type ctxKey string
const slogKey ctxKey = "slog"
func Base() *slog.Logger {
h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})
return slog.New(h)
}
func With(ctx context.Context, l *slog.Logger) context.Context {
return context.WithValue(ctx, slogKey, l)
}
func From(ctx context.Context) *slog.Logger {
if v := ctx.Value(slogKey); v != nil {
if l, ok := v.(*slog.Logger); ok {
return l
}
}
return slog.New(slog.NewTextHandler(os.Stdout, nil))
}
1 file · go
Explain with highlit
I’ve started using log/slog for services that want structured logs without a heavy dependency. The key is treating the request logger as data: create a base logger with JSON output, then derive a request logger with fields like request_id and path. I avoid logging raw request bodies by default and instead log stable identifiers and error codes. Because slog uses context.Context, it’s easy to pass the logger down without changing every function signature. In production, this makes logs far more useful for queries like “show all errors for request_id=...” and it keeps log formatting consistent across packages. It’s a small wrapper, but it makes the whole codebase feel more coherent.
Related snips
go
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
go
observability
build
by Leah Thompson
1 tab
typescript
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
typescript
reliability
retry
by codesnips
2 tabs
go
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
go
postgres
transactions
by Leah Thompson
1 tab
rust
use tracing::{info, instrument};
#[instrument]
fn process_request(user_id: u64) {
info!(user_id, "Processing request");
// Work happens here
tracing for structured logging and distributed tracing
rust
observability
tracing
by Marcus Chen
1 tab
go
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
go
aws
s3
by Leah Thompson
1 tab
go
package deps
import (
"net"
"net/http"
"time"
HTTP client tuned for production: timeouts, transport, and connection reuse
go
http
client
by Leah Thompson
1 tab
Share this code
Here's the card — post it anywhere.