Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to set timezone when using ConsoleWriter? #521

Open
chuan137 opened this issue Feb 10, 2023 · 2 comments
Open

How to set timezone when using ConsoleWriter? #521

chuan137 opened this issue Feb 10, 2023 · 2 comments

Comments

@chuan137
Copy link

I tried to set the TimestampFunc, and it does change the json output, but not working on the console writer

	zerolog.TimestampFunc = func() time.Time {
		return time.Now().UTC()
	}

and here is my logs looks like, they are printed from same run with different logger. The timestamp jumps by 1hr because I am in the +1 timezone. The timestamp in json is correct UTC time, but the console writer logs the local time. How can I make it also log the UTC time?

{"level":"info","time":"2023-02-10T23:03:52Z","message":"config and template dir: ./"}
{"level":"info","time":"2023-02-10T23:03:52Z","message":"observe metrics from http://localhost:9090"}
2023-02-11T00:03:52+01:00 DBG pkg/netappsd/queue.go:67 > queue readiness = false
@luxinxinxin
Copy link

you can change /etc/localtime in the system directory.

@ramitmittal
Copy link

You can use a custom formatter for timestamps with ConsoleWriter.

cw := zerolog.NewConsoleWriter(func(w *zerolog.ConsoleWriter) {
	w.FormatTimestamp = func(i interface{}) string {
		if v, ok := i.(string); ok {
			if ts, err := time.ParseInLocation(time.RFC3339, v, time.Local); err == nil {
				return ts.UTC().Format(time.RFC3339)
			}
		}
		return "<nil>"
	}
})
log.Logger = log.Output(cw)

This was adapted from consoleDefaultFormatTimestamp in console.go. Link. Use that as a reference and make modifications wherever required.
I have assumed that you're using ConsoleWriter only in development.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants