Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for hex-encoded bytes #42

Merged
merged 3 commits into from
Mar 15, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions array.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package zerolog

import (
"encoding/hex"
"sync"
"time"

Expand Down Expand Up @@ -64,6 +65,12 @@ func (a *Array) Bytes(val []byte) *Array {
return a
}

// Hex append the val as a hex string to the array.
func (a *Array) Hex(val []byte) *Array {
a.buf = json.AppendString(append(a.buf, ','), hex.EncodeToString(val))
return a
}

// Err append the err as a string to the array.
func (a *Array) Err(err error) *Array {
a.buf = json.AppendError(append(a.buf, ','), err)
Expand Down
4 changes: 3 additions & 1 deletion array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ func TestArray(t *testing.T) {
Float32(11).
Float64(12).
Str("a").
Bytes([]byte("b")).
Hex([]byte{0x1f}).
Time(time.Time{}).
Dur(0)
want := `[true,1,2,3,4,5,6,7,8,9,10,11,12,"a","0001-01-01T00:00:00Z",0]`
want := `[true,1,2,3,4,5,6,7,8,9,10,11,12,"a","b","1f","0001-01-01T00:00:00Z",0]`
if got := string(a.write([]byte{})); got != want {
t.Errorf("Array.write()\ngot: %s\nwant: %s", got, want)
}
Expand Down
7 changes: 7 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package zerolog

import (
"encoding/hex"
"io/ioutil"
"time"

Expand Down Expand Up @@ -73,6 +74,12 @@ func (c Context) Strs(key string, vals []string) Context {
return c
}

// Hex adds the field key with val as a hex string to the logger context.
func (c Context) Hex(key string, val []byte) Context {
c.l.context = json.AppendString(json.AppendKey(c.l.context, key), hex.EncodeToString(val))
return c
}

// Bytes adds the field key with val as a []byte to the logger context.
func (c Context) Bytes(key string, val []byte) Context {
c.l.context = json.AppendBytes(json.AppendKey(c.l.context, key), val)
Expand Down
10 changes: 10 additions & 0 deletions event.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package zerolog

import (
"encoding/hex"
"fmt"
"os"
"runtime"
Expand Down Expand Up @@ -219,6 +220,15 @@ func (e *Event) Bytes(key string, val []byte) *Event {
return e
}

// Hex adds the field key with val as a hex string to the *Event context.
func (e *Event) Hex(key string, val []byte) *Event {
if e == nil {
return e
}
e.buf = json.AppendString(json.AppendKey(e.buf, key), hex.EncodeToString(val))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could create a json.AppendHex that just does:

func AppendHex(buf, val []byte) []byte {
    const hextable = "0123456789abcdef"
    for _, v := range val {
        buf = append(buf, hextable[v>>4], hextable[v&0x0f])
    }
    return buf
}

This would avoid the slice heap allocation done by hex.EncodeToString.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. I also added comments for all the AppendXXX(...) functions that were missing them to shut up the linter.

return e
}

// RawJSON adds already encoded JSON to the log line under key.
//
// No sanity check is performed on b; it must not contain carriage returns and
Expand Down
10 changes: 7 additions & 3 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ func TestInfo(t *testing.T) {
func TestWith(t *testing.T) {
out := &bytes.Buffer{}
ctx := New(out).With().
Str("foo", "bar").
Str("string", "foo").
Bytes("bytes", []byte("bar")).
Hex("hex", []byte{0x12, 0xef}).
RawJSON("json", []byte(`{"some":"json"}`)).
AnErr("some_err", nil).
Err(errors.New("some error")).
Expand All @@ -99,7 +101,7 @@ func TestWith(t *testing.T) {
caller := fmt.Sprintf("%s:%d", file, line+3)
log := ctx.Caller().Logger()
log.Log().Msg("")
if got, want := out.String(), `{"foo":"bar","json":{"some":"json"},"error":"some error","bool":true,"int":1,"int8":2,"int16":3,"int32":4,"int64":5,"uint":6,"uint8":7,"uint16":8,"uint32":9,"uint64":10,"float32":11,"float64":12,"time":"0001-01-01T00:00:00Z","caller":"`+caller+`"}`+"\n"; got != want {
if got, want := out.String(), `{"string":"foo","bytes":"bar","hex":"12ef","json":{"some":"json"},"error":"some error","bool":true,"int":1,"int8":2,"int16":3,"int32":4,"int64":5,"uint":6,"uint8":7,"uint16":8,"uint32":9,"uint64":10,"float32":11,"float64":12,"time":"0001-01-01T00:00:00Z","caller":"`+caller+`"}`+"\n"; got != want {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
}
}
Expand Down Expand Up @@ -143,6 +145,7 @@ func TestFields(t *testing.T) {
Caller().
Str("string", "foo").
Bytes("bytes", []byte("bar")).
Hex("hex", []byte{0x12, 0xef}).
RawJSON("json", []byte(`{"some":"json"}`)).
AnErr("some_err", nil).
Err(errors.New("some error")).
Expand All @@ -163,7 +166,7 @@ func TestFields(t *testing.T) {
Time("time", time.Time{}).
TimeDiff("diff", now, now.Add(-10*time.Second)).
Msg("")
if got, want := out.String(), `{"caller":"`+caller+`","string":"foo","bytes":"bar","json":{"some":"json"},"error":"some error","bool":true,"int":1,"int8":2,"int16":3,"int32":4,"int64":5,"uint":6,"uint8":7,"uint16":8,"uint32":9,"uint64":10,"float32":11,"float64":12,"dur":1000,"time":"0001-01-01T00:00:00Z","diff":10000}`+"\n"; got != want {
if got, want := out.String(), `{"caller":"`+caller+`","string":"foo","bytes":"bar","hex":"12ef","json":{"some":"json"},"error":"some error","bool":true,"int":1,"int8":2,"int16":3,"int32":4,"int64":5,"uint":6,"uint8":7,"uint16":8,"uint32":9,"uint64":10,"float32":11,"float64":12,"dur":1000,"time":"0001-01-01T00:00:00Z","diff":10000}`+"\n"; got != want {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
}
}
Expand Down Expand Up @@ -256,6 +259,7 @@ func TestFieldsDisabled(t *testing.T) {
log.Debug().
Str("string", "foo").
Bytes("bytes", []byte("bar")).
Hex("hex", []byte{0x12, 0xef}).
AnErr("some_err", nil).
Err(errors.New("some error")).
Bool("bool", true).
Expand Down