blob: 0e10b8a5aa8e948c9d989238bb3968a609ca97b0 [file] [log] [blame]
Rohan Agrawalc32d9932020-06-15 11:01:47 +00001// 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
15package spanlog
16
17import (
18 "encoding/json"
19 "fmt"
20
21 "github.com/opentracing/opentracing-go/log"
22)
23
24type fieldsAsMap map[string]string
25
26// MaterializeWithJSON converts log Fields into JSON string
27// TODO refactor into pluggable materializer
28func 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
39func (ml fieldsAsMap) EmitString(key, value string) {
40 ml[key] = value
41}
42
43func (ml fieldsAsMap) EmitBool(key string, value bool) {
44 ml[key] = fmt.Sprintf("%t", value)
45}
46
47func (ml fieldsAsMap) EmitInt(key string, value int) {
48 ml[key] = fmt.Sprintf("%d", value)
49}
50
51func (ml fieldsAsMap) EmitInt32(key string, value int32) {
52 ml[key] = fmt.Sprintf("%d", value)
53}
54
55func (ml fieldsAsMap) EmitInt64(key string, value int64) {
56 ml[key] = fmt.Sprintf("%d", value)
57}
58
59func (ml fieldsAsMap) EmitUint32(key string, value uint32) {
60 ml[key] = fmt.Sprintf("%d", value)
61}
62
63func (ml fieldsAsMap) EmitUint64(key string, value uint64) {
64 ml[key] = fmt.Sprintf("%d", value)
65}
66
67func (ml fieldsAsMap) EmitFloat32(key string, value float32) {
68 ml[key] = fmt.Sprintf("%f", value)
69}
70
71func (ml fieldsAsMap) EmitFloat64(key string, value float64) {
72 ml[key] = fmt.Sprintf("%f", value)
73}
74
75func (ml fieldsAsMap) EmitObject(key string, value interface{}) {
76 ml[key] = fmt.Sprintf("%+v", value)
77}
78
79func (ml fieldsAsMap) EmitLazyLogger(value log.LazyLogger) {
80 value(ml)
81}