Matteo Scandolo | a428586 | 2020-12-01 18:10:10 -0800 | [diff] [blame] | 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 | |
| 15 | package spanlog |
| 16 | |
| 17 | import ( |
| 18 | "encoding/json" |
| 19 | "fmt" |
| 20 | |
| 21 | "github.com/opentracing/opentracing-go/log" |
| 22 | ) |
| 23 | |
| 24 | type fieldsAsMap map[string]string |
| 25 | |
| 26 | // MaterializeWithJSON converts log Fields into JSON string |
| 27 | // TODO refactor into pluggable materializer |
| 28 | func MaterializeWithJSON(logFields []log.Field) ([]byte, error) { |
| 29 | fields := fieldsAsMap(make(map[string]string, len(logFields))) |
| 30 | for _, field := range logFields { |
| 31 | field.Marshal(fields) |
| 32 | } |
| 33 | if event, ok := fields["event"]; ok && len(fields) == 1 { |
| 34 | return []byte(event), nil |
| 35 | } |
| 36 | return json.Marshal(fields) |
| 37 | } |
| 38 | |
| 39 | func (ml fieldsAsMap) EmitString(key, value string) { |
| 40 | ml[key] = value |
| 41 | } |
| 42 | |
| 43 | func (ml fieldsAsMap) EmitBool(key string, value bool) { |
| 44 | ml[key] = fmt.Sprintf("%t", value) |
| 45 | } |
| 46 | |
| 47 | func (ml fieldsAsMap) EmitInt(key string, value int) { |
| 48 | ml[key] = fmt.Sprintf("%d", value) |
| 49 | } |
| 50 | |
| 51 | func (ml fieldsAsMap) EmitInt32(key string, value int32) { |
| 52 | ml[key] = fmt.Sprintf("%d", value) |
| 53 | } |
| 54 | |
| 55 | func (ml fieldsAsMap) EmitInt64(key string, value int64) { |
| 56 | ml[key] = fmt.Sprintf("%d", value) |
| 57 | } |
| 58 | |
| 59 | func (ml fieldsAsMap) EmitUint32(key string, value uint32) { |
| 60 | ml[key] = fmt.Sprintf("%d", value) |
| 61 | } |
| 62 | |
| 63 | func (ml fieldsAsMap) EmitUint64(key string, value uint64) { |
| 64 | ml[key] = fmt.Sprintf("%d", value) |
| 65 | } |
| 66 | |
| 67 | func (ml fieldsAsMap) EmitFloat32(key string, value float32) { |
| 68 | ml[key] = fmt.Sprintf("%f", value) |
| 69 | } |
| 70 | |
| 71 | func (ml fieldsAsMap) EmitFloat64(key string, value float64) { |
| 72 | ml[key] = fmt.Sprintf("%f", value) |
| 73 | } |
| 74 | |
| 75 | func (ml fieldsAsMap) EmitObject(key string, value interface{}) { |
| 76 | ml[key] = fmt.Sprintf("%+v", value) |
| 77 | } |
| 78 | |
| 79 | func (ml fieldsAsMap) EmitLazyLogger(value log.LazyLogger) { |
| 80 | value(ml) |
| 81 | } |