Skip to content

Allow context.Context based values in logger #47

@applejag

Description

@applejag

This is just an idea. Maybe it's good, maybe it's not.

The idea is to allow writing fields to context.Context and then let a logger event to read fields from it.

Usage would look something like this:

var log = logger.New()

func main() {
	ctx := context.Background()

	ctx := log.Prepare().
	  WithInt("myInt", 123).
		WithString("myStr", "foo").
		AsContext(ctx)

	doStuff(ctx)
}

func doStuff(ctx context.Context) {
	ctx := log.Prepare().
		WithBool("yes", true).
		AsContext(ctx)

	doInnerStuff(ctx)
}

func doInnerStuff(ctx context.Context) {
	log.Info().
		WithContext(ctx).
		WithString("lorem", "ipsum").
		Message("Hello.")
}

Would log something like:

[INFO ] Hello.  myInt=123  myStr=foo  yes=true  lorem=ipsum

Would be good if scope could be added in a similar way as well. This could potentially restructure how scopes are added, that instead of using logger.NewScoped that we instead only provide scope via context.Context as yet another field. Such as:

var log = logger.New()

func main() {
	ctx := log.Prepare().
	  WithScope("main").
		AsContext(context.Background())

	doStuff(ctx)
}

func doStuff(ctx context.Context) {
	ctx := log.Prepare().
		WithScope("doStuff").
		AsContext(ctx)

	doInnerStuff(ctx)
}

func doInnerStuff(ctx context.Context) {
	log.Info().
		WithContext(ctx).
		WithScope("doInnerStuff").
		Message("Hello.")
}

Which would result in:

[INFO |main/doStuff/doInnerStuff] Hello.

However the scope change would destroy how our consolepretty.Config.ScopeMinLengthAuto works, as it's much more difficult to foresee the scopes lengths. Maybe worth removing that config field, and force scopes to rely on a fixed length?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestprio/0Lowest priority. "Wishful thinking"

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions