diff --git a/log/field.go b/log/field.go index a340aed..5bc47b6 100644 --- a/log/field.go +++ b/log/field.go @@ -1,6 +1,9 @@ package log -import "math" +import ( + "fmt" + "math" +) type fieldType int @@ -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) @@ -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()) +} diff --git a/log/field_test.go b/log/field_test.go new file mode 100644 index 0000000..d301e49 --- /dev/null +++ b/log/field_test.go @@ -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) + } + } +}