Skip to content

Releases: cyrusaf/ctxlog

Subsequent anchor points on a ctx with an existing anchor point should noop

05 Nov 00:33
5e8b294
Compare
Choose a tag to compare

See #10.

Previously, if you called AnchorGlobalAttrs on a ctx with an existing anchor point, it would reset and clear all existing global attrs. This change chooses not to overwrite the existing anchor point, but rather re-use it. I considered creating a new anchor point and copying over fields, but thought the approach of maintaining the previous anchor point would be more common. We can always add a method to reset the anchor point if that is a needed use case.

Better support for re-using an slog.Attr with an identical key

14 Mar 23:05
Compare
Choose a tag to compare

Changes the backing store to a map[string]slog.Attr rather than a []slog.Attr to better support overwriting attrs with the same key.

Create global attributes

14 Mar 15:08
9798c8d
Compare
Choose a tag to compare

Sometimes you want a sub-function to be able to "pass back" attributes to the parent. An example of this is when using middleware to log errors. In the situation below, the handler h may handle parsing the req and pull out certain fields that should be logged if there is an error. Unfortunately, because WithAttrs(...) only attaches the attrs to a child context, the parent function will not have access to these attrs.

func logMiddleware(ctx context.Context, h Handler, req []byte) {
    err := h(ctx, req)
    if err != nil {
        slog.ErrorContext(ctx, "request error")
    }
}

ctxlog provides a way to pass back these attributes for logging through global attributes.

func logMiddleware(ctx context.Context, h Handler, req []byte) {
    // First, set the anchor point/root of global attrs. This allows us to
    // scope global attrs to each request.
    ctx = ctxlog.AnchorGlobalAttrs(ctx) 
    err := h(ctx, req)
    if err != nil {
        slog.ErrorContext(ctx, "request error")
    }
}

func myHandler(ctx context.Context, req []byte) error {
    parsedReq := parseRequest(req)

    // Use ctxlog.WithGlobalAttrs to "pass back" attrs to the anchor point
    ctx = ctxlog.WithGlobalAttrs(ctx, slog.String("request_id", parsedReq.request_id))
    // ...
    return nil
}

Add support for WithAttrs

12 Sep 16:33
5770792
Compare
Choose a tag to compare

Fixes issue mentioned in #3 where .WithAttrs and .WithGroup were not implemented. FYI there is some strange behavior in .WithGroup mentioned in #5.

Use log/slog with Go 1.21 release

09 Aug 17:11
aa646f6
Compare
Choose a tag to compare

Moves from the experimental x/exp/slog to the stdlib log/slog with the release of slog in Go 1.21.