Skip to content
This repository has been archived by the owner on May 23, 2023. It is now read-only.

Commit

Permalink
Add convenience methods to log.Field
Browse files Browse the repository at this point in the history
Currently the only way to print a `Field` is to define an `Encoder`. This is a
lot of code to write, especially if it's needed just for debugging or a quick
test. Adding a `Value()` method that returns the value as an `interface{}`
(which can be passed to `fmt.Print` functions), as well as a `String()` method.

Also exporting the key field.
  • Loading branch information
RaduBerinde committed Sep 27, 2016
1 parent 0c3154a commit 2250288
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 2 deletions.
45 changes: 43 additions & 2 deletions log/field.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package log

import "math"
import (
"fmt"
"math"
)

type fieldType int

Expand All @@ -20,7 +23,7 @@ const (
)

// Field instances are constructed via LogBool, LogString, and so on.
// Tracing implementations may then handle them via the Field.Process
// Tracing implementations may then handle them via the Field.Marshal
// method.
//
// "heavily influenced by" (i.e., partially stolen from)
Expand Down Expand Up @@ -198,3 +201,41 @@ func (lf Field) Marshal(visitor Encoder) {
visitor.EmitLazyLogger(lf.interfaceVal.(LazyLogger))
}
}

// Key returns the field's key.
func (lf Field) Key() string {
return lf.key
}

// Value returns the field's value as interface{}.
func (lf Field) Value() interface{} {
switch lf.fieldType {
case stringType:
return lf.stringVal
case boolType:
return lf.numericVal != 0
case intType:
return int(lf.numericVal)
case int32Type:
return int32(lf.numericVal)
case int64Type:
return int64(lf.numericVal)
case uint32Type:
return uint32(lf.numericVal)
case uint64Type:
return uint64(lf.numericVal)
case float32Type:
return math.Float32frombits(uint32(lf.numericVal))
case float64Type:
return math.Float64frombits(uint64(lf.numericVal))
case errorType, objectType, lazyLoggerType:
return lf.interfaceVal
default:
return nil
}
}

// String returns a string representation of the key and value.
func (lf Field) String() string {
return fmt.Sprint(lf.key, ":", lf.Value())
}
35 changes: 35 additions & 0 deletions log/field_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package log

import (
"fmt"
"testing"
)

func TestFieldString(t *testing.T) {
testCases := []struct {
field Field
expected string
}{
{
field: String("key", "value"),
expected: "key:value",
},
{
field: Bool("key", true),
expected: "key:true",
},
{
field: Int("key", 5),
expected: "key:5",
},
{
field: Error(fmt.Errorf("err msg")),
expected: "error:err msg",
},
}
for i, tc := range testCases {
if str := tc.field.String(); str != tc.expected {
t.Errorf("%d: expected '%s', got '%s'", i, tc.expected, str)
}
}
}

0 comments on commit 2250288

Please sign in to comment.