Skip to content

README discrepancy; .Ctx(ctx) after event verses prior to event when using hooks #685

Open
@huntergoff

Description

@huntergoff

According to the context.Context part of the readme, when attaching a Go context, this is the example given (notice that the context is added prior to the event):

logger := zerolog.Ctx(ctx)
logger.Info().Msg("Hello")

Whereas, the second form of a Go context integration has a small, seemingly insignificant line, about passing the current context.Context into the logged event, which is then retrieved from hooks. The example given:

ctx := context.Background()
// Use the Ctx function to make the context available to the hook
logger.Info().Ctx(ctx).Msg("Hello")

Spent some time debugging this yesterday since our repository pattern was similar to the first, where most logs where structured like below:

log.Ctx(ctx).Info().Msg("")

When I implemented tracingHooks to append two Ids from context, they never appeared (they were logged as nil). It was not until a closer reading clued me towards using context AFTER the event, which then worked. Another example below:

Context prior to the event (i.e. log.Ctx(ctx).Info())::

Context in hook: context.Background
2024-08-28T09:38:05-05:00 INF foo/bar.go:1 > id_1=00000000-0000-0000-0000-000000000000 id_2=00000000-0000-0000-0000-000000000000

Context after the event (i.e. log.Info().Ctx(ctx)):

Context in hook: context.Background.WithValue(zerolog.ctxKey, *zerolog.Logger).WithValue(id_1, 1f3c4e8d-18f9-4e71-9458-3bc4779600ee).WithValue(id_2, 45cc934d-4b2e-42ad-ab18-fc7a6d81546a)
2024-08-28T09:38:05-05:00 INFfoo/bar:1 > id_1=45cc934d-4b2e-42ad-ab18-fc7a6d81546a id_2=1f3c4e8d-18f9-4e71-9458-3bc4779600ee

I am curious to why this is the case, and requesting that the README be updated to call attention to this to help those after myself. If easiest, I can also submit a PR with a README callout, but would prefer to understand this discrepancy at a deeper level first.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions