json.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (c) 2017 Uber Technologies, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package spanlog
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "github.com/opentracing/opentracing-go/log"
  19. )
  20. type fieldsAsMap map[string]string
  21. // MaterializeWithJSON converts log Fields into JSON string
  22. // TODO refactor into pluggable materializer
  23. func MaterializeWithJSON(logFields []log.Field) ([]byte, error) {
  24. fields := fieldsAsMap(make(map[string]string, len(logFields)))
  25. for _, field := range logFields {
  26. field.Marshal(fields)
  27. }
  28. if event, ok := fields["event"]; ok && len(fields) == 1 {
  29. return []byte(event), nil
  30. }
  31. return json.Marshal(fields)
  32. }
  33. func (ml fieldsAsMap) EmitString(key, value string) {
  34. ml[key] = value
  35. }
  36. func (ml fieldsAsMap) EmitBool(key string, value bool) {
  37. ml[key] = fmt.Sprintf("%t", value)
  38. }
  39. func (ml fieldsAsMap) EmitInt(key string, value int) {
  40. ml[key] = fmt.Sprintf("%d", value)
  41. }
  42. func (ml fieldsAsMap) EmitInt32(key string, value int32) {
  43. ml[key] = fmt.Sprintf("%d", value)
  44. }
  45. func (ml fieldsAsMap) EmitInt64(key string, value int64) {
  46. ml[key] = fmt.Sprintf("%d", value)
  47. }
  48. func (ml fieldsAsMap) EmitUint32(key string, value uint32) {
  49. ml[key] = fmt.Sprintf("%d", value)
  50. }
  51. func (ml fieldsAsMap) EmitUint64(key string, value uint64) {
  52. ml[key] = fmt.Sprintf("%d", value)
  53. }
  54. func (ml fieldsAsMap) EmitFloat32(key string, value float32) {
  55. ml[key] = fmt.Sprintf("%f", value)
  56. }
  57. func (ml fieldsAsMap) EmitFloat64(key string, value float64) {
  58. ml[key] = fmt.Sprintf("%f", value)
  59. }
  60. func (ml fieldsAsMap) EmitObject(key string, value interface{}) {
  61. ml[key] = fmt.Sprintf("%+v", value)
  62. }
  63. func (ml fieldsAsMap) EmitLazyLogger(value log.LazyLogger) {
  64. value(ml)
  65. }