| 393 | } |
| 394 | |
| 395 | func (s *SugaredLogger) sweetenFields(args []interface{}) []Field { |
| 396 | if len(args) == 0 { |
| 397 | return nil |
| 398 | } |
| 399 | |
| 400 | var ( |
| 401 | // Allocate enough space for the worst case; if users pass only structured |
| 402 | // fields, we shouldn't penalize them with extra allocations. |
| 403 | fields = make([]Field, 0, len(args)) |
| 404 | invalid invalidPairs |
| 405 | seenError bool |
| 406 | ) |
| 407 | |
| 408 | for i := 0; i < len(args); { |
| 409 | // This is a strongly-typed field. Consume it and move on. |
| 410 | if f, ok := args[i].(Field); ok { |
| 411 | fields = append(fields, f) |
| 412 | i++ |
| 413 | continue |
| 414 | } |
| 415 | |
| 416 | // If it is an error, consume it and move on. |
| 417 | if err, ok := args[i].(error); ok { |
| 418 | if !seenError { |
| 419 | seenError = true |
| 420 | fields = append(fields, Error(err)) |
| 421 | } else { |
| 422 | s.base.Error(_multipleErrMsg, Error(err)) |
| 423 | } |
| 424 | i++ |
| 425 | continue |
| 426 | } |
| 427 | |
| 428 | // Make sure this element isn't a dangling key. |
| 429 | if i == len(args)-1 { |
| 430 | s.base.Error(_oddNumberErrMsg, Any("ignored", args[i])) |
| 431 | break |
| 432 | } |
| 433 | |
| 434 | // Consume this value and the next, treating them as a key-value pair. If the |
| 435 | // key isn't a string, add this pair to the slice of invalid pairs. |
| 436 | key, val := args[i], args[i+1] |
| 437 | if keyStr, ok := key.(string); !ok { |
| 438 | // Subsequent errors are likely, so allocate once up front. |
| 439 | if cap(invalid) == 0 { |
| 440 | invalid = make(invalidPairs, 0, len(args)/2) |
| 441 | } |
| 442 | invalid = append(invalid, invalidPair{i, key, val}) |
| 443 | } else { |
| 444 | fields = append(fields, Any(keyStr, val)) |
| 445 | } |
| 446 | i += 2 |
| 447 | } |
| 448 | |
| 449 | // If we encountered any invalid key-value pairs, log an error. |
| 450 | if len(invalid) > 0 { |
| 451 | s.base.Error(_nonStringKeyErrMsg, Array("invalid", invalid)) |
| 452 | } |