i'm using zerolog for logging and got complain because the format log not same like before, i'm trying refactor from other language to golang. is possible change position level and timestamp ?
this is my code : `
consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout, NoColor:
true, TimeFormat: time.RFC3339}
consoleWriter.FormatLevel = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("[ %-6s] -", i))
}
consoleWriter.FormatTimestamp = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("[%s]", i))
}
if cfg.Logger.WriteLogger {
multi = zerolog.MultiLevelWriter(consoleWriter, file)
} else {
defer file.Close()
multi = zerolog.MultiLevelWriter(consoleWriter)
}
logger := zerolog.New(multi).Level(zerolog.TraceLevel).
With().
Timestamp().
Logger()
logger.Info().Msg("this is message")
`
and i got result :
[2024-01-16T13:24:05+07:00] [ INFO ] - this is message
Is it possible to change the position so that the result looks like:
[ INFO ] [2024-01-16T13:24:05+07:00] - this is message
Thank you.
You can use PartsOrder to do this; you will also need to tweak your formatters to get the -
in the right place (playground).
func main() {
consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout, NoColor: true, TimeFormat: time.RFC3339}
consoleWriter.FormatLevel = func(i interface{}) string {
return strings.ToUpper(fmt.Sprintf("[ %-6s]", i))
}
//consoleWriter.FormatTimestamp = func(i interface{}) string {
// return strings.ToUpper(fmt.Sprintf("[%s] -", i))
//}
consoleWriter.TimeFormat = "[" + time.RFC3339 + "] - "
consoleWriter.PartsOrder = []string{
zerolog.LevelFieldName,
zerolog.TimestampFieldName,
zerolog.CallerFieldName,
zerolog.MessageFieldName,
}
logger := zerolog.New(consoleWriter).Level(zerolog.TraceLevel).
With().
Timestamp().
Logger()
logger.Info().Msg("this is message")
}
Output:
[ INFO ] [2024-01-16T21:11:39+13:00] - this is message