rs / zerolog

Zero Allocation JSON Logger
MIT License
10.41k stars 567 forks source link

[Q] How to remove the timestamp from a customized handler? #517

Closed wsw70 closed 1 year ago

wsw70 commented 1 year ago

This is a beginner question, sorry if it is obvious but there are elements of Go that I still struggle with.

I use (and love!) zerolog in all my backend code, by importing github.com/rs/zerolog/log and then log.Info().Msg("thank you"). It works great to create structured (JSON) logs.

I am now developing a cli and these logs are less useful because they will be read by humans. The README suggests

log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})

This is great - the output is much better.

I want to customize further, though and the resolution I just below in the README.

My problem: up to then, I was modifying the log handler which was fine because I could do that for instance in an init() routine. With further customization, I went for

var log zerolog.Logger

func init() {
    output := zerolog.ConsoleWriter{Out: os.Stdout}
    output.FormatLevel = func(i interface{}) string {
        return strings.ToUpper(fmt.Sprintf("%-6s", i))
    }
    output.FormatMessage = func(i interface{}) string {
        return fmt.Sprintf(" %s", i)
    }

    log = zerolog.New(output).With().Logger()
}

This gives the output

<nil> INFO    wrote something

So despite not using .With().Timestamp(), the timestamp still wants to be there. How to completely switch it off?

azrehman commented 1 year ago

zerolog.ConsoleWriter includes the timestamp as default so use PartsExclude to remove the timestamp: log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, PartsExclude: []string{"time"}})