Skip to content

Type values in arrays #729

@TylerHendrickson

Description

@TylerHendrickson

I noticed that zerolog.Array does not provide a method for adding a value's type to the array using reflection. I'd expected this to be similar to using the zerolog.Event.Type() method, but within an array, e.g.

zerolog.Arr().Type("foo").Type(time.Now())

to get the following structure:

["string","time.Time"]

In real-world terms, something like this would be useful for scenarios such as in Kong's approach to type-based bindings. A contrived example:

// (Example based on https://github.com/alecthomas/kong?tab=readme-ov-file#the-bind-option)

type CLI struct {
	Debug bool `help:"Enable debug mode."`

	Rm RmCmd `cmd:"" help:"Remove files."`
	Ls LsCmd `cmd:"" help:"List paths."`
}

type AuthorName string

// ...

func main() {
	logger := zerolog.New(os.Stderr).With().
		Logger().
		Level(zerolog.InfoLevel)

	var cli CLI
	ctx := kong.Parse(&cli)
	author := AuthorName("penguin")
	ctx.Bind(logger, author)
	logger.Info().  // {"level":"info","bound":["zerolog.Logger","main.AuthorName"],"message":"added bindings to app context"}
		Array("bound", zerolog.Arr().Type(logger).Type(author)).
		Msg("added bindings to application context")
	if err := ctx.Run(); err != nil {
		logger.Fatal().Err(err)
	}
}

Is there another way to accomplish this? If not, I'm happy to contribute a pull request for consideration.

Thank you!

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