HN2new | past | comments | ask | show | jobs | submitlogin

It's nice to have this in the standard library, but it doesn't solve any existing pain points around structured log metadata and contexts. We use zap [0] and store a zap logger on the request context which allows different parts of the request pipeline to log with things like tenantId, traceId, and correlationId automatically appended. But getting a logger off the context is annoying, leads to inconsistent logging practices, and creates a logger dependency throughout most of our Go code.

[0] https://github.com/uber-go/zap



log/slog package essentially delegates writing log messages to some "handler" interface. The key method is:

    Handle(context.Context, Record) error
This method has access to the context, which means you can get the logging handler to extract values from the context. Instead of storing the logger on the context, you can extract the traceId, etc values from the context and log those.

It's a little bit involved to write a whole logger from scratch, but you can 'wrap' the existing logger handlers and include values from the context relatively easily.

There are examples in this project (which aims to help solve your usecase): https://github.com/zknill/slogmw


Here's an example of extracting context values in a custom slog handler:

https://github.com/indexsupply/x/blob/main/wslog/slog_test.g...


This is addressed in the article.

> As the call to LogAttrs shows, you can pass a context.Context to some log functions so a handler can extract context information like trace IDs.

I’m not a fan of slog’s syntax, but the convenience of having it in the stdlib trumps that, for me.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: