Home  >  Article  >  Backend Development  >  Change location level and timestamp Zerolog golang

Change location level and timestamp Zerolog golang

王林
王林forward
2024-02-12 18:09:051257browse

更改位置级别和时间戳 Zerolog golang

Question content

I'm using Zerolog for logging but I'm getting complaints because the log format is different from before and I'm trying to refactor from another language to golang. Is it possible to change the location 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")

`

I got the result:

[2024-01-16T13:24:05 07:00] [Message] - This is the message

块引用>

Is it possible to change the position so that the result looks like:

[ INFO ] [2024-01-16T13:24:05 07:00] - This is the message

块引用>

Thanks.

Workaround

You can use PartsOrder to do this; you will also need to adjust the formatter so that - is in the correct location ( 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

The above is the detailed content of Change location level and timestamp Zerolog golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete