Fix the ConsoleWriter default parts order (#113)

In order to prevent incorrect output when somebody uses a different name eg. for the "MessageFieldName",
the `consoleDefaultPartsOrder` variable has been switched to a function, which is called in `Write()`,
in order to pick up the custom name.

Related: rs/zerolog#92
This commit is contained in:
Karel Minarik 2018-11-07 09:39:38 -08:00 committed by Olivier Poitrey
parent 96f91bb4f5
commit a4c54e5d8b
1 changed files with 9 additions and 7 deletions

View File

@ -38,11 +38,13 @@ var (
consoleDefaultTimeFormat = time.Kitchen consoleDefaultTimeFormat = time.Kitchen
consoleDefaultFormatter = func(i interface{}) string { return fmt.Sprintf("%s", i) } consoleDefaultFormatter = func(i interface{}) string { return fmt.Sprintf("%s", i) }
consoleDefaultPartsOrder = []string{ consoleDefaultPartsOrder = func() []string {
TimestampFieldName, return []string{
LevelFieldName, TimestampFieldName,
CallerFieldName, LevelFieldName,
MessageFieldName, CallerFieldName,
MessageFieldName,
}
} }
consoleNoColor = false consoleNoColor = false
@ -82,7 +84,7 @@ func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter {
w := ConsoleWriter{ w := ConsoleWriter{
Out: os.Stdout, Out: os.Stdout,
TimeFormat: consoleDefaultTimeFormat, TimeFormat: consoleDefaultTimeFormat,
PartsOrder: consoleDefaultPartsOrder, PartsOrder: consoleDefaultPartsOrder(),
} }
for _, opt := range options { for _, opt := range options {
@ -95,7 +97,7 @@ func NewConsoleWriter(options ...func(w *ConsoleWriter)) ConsoleWriter {
// Write transforms the JSON input with formatters and appends to w.Out. // Write transforms the JSON input with formatters and appends to w.Out.
func (w ConsoleWriter) Write(p []byte) (n int, err error) { func (w ConsoleWriter) Write(p []byte) (n int, err error) {
if w.PartsOrder == nil { if w.PartsOrder == nil {
w.PartsOrder = consoleDefaultPartsOrder w.PartsOrder = consoleDefaultPartsOrder()
} }
if w.TimeFormat == "" && consoleTimeFormat != consoleDefaultTimeFormat { if w.TimeFormat == "" && consoleTimeFormat != consoleDefaultTimeFormat {
consoleTimeFormat = consoleDefaultTimeFormat consoleTimeFormat = consoleDefaultTimeFormat