Skip to content

Commit

Permalink
Add zlog.Field
Browse files Browse the repository at this point in the history
Because this:

	zlog.Field("site", site.ID)

Is just much nicer than:

	zlog.Fields(zlog.F{"site": site.ID})
  • Loading branch information
arp242 committed Nov 7, 2019
1 parent 6f91b37 commit 65d5560
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
8 changes: 7 additions & 1 deletion zlog.go
Expand Up @@ -119,6 +119,7 @@ type (
func Module(m string) Log { return Log{Modules: []string{m}, since: time.Now()} }

func SetDebug(m ...string) Log { return Log{DebugModules: m} }
func Field(k string, v interface{}) Log { return Log{Data: F{k: v}} }
func Fields(f F) Log { return Log{Data: f} }
func Print(v ...interface{}) { Log{}.Print(v...) }
func Printf(f string, v ...interface{}) { Log{}.Printf(f, v...) }
Expand Down Expand Up @@ -150,7 +151,7 @@ func (l Log) Module(m string) Log {
return l
}

// Fields sets the log data.
// Fields append data to the Log object.
func (l Log) Fields(f F) Log {
if l.Data == nil {
l.Data = f
Expand All @@ -163,6 +164,11 @@ func (l Log) Fields(f F) Log {
return l
}

// Field sets one data field.
func (l Log) Field(k string, v interface{}) Log {
return l.Fields(F{k: v})
}

// Print an informational error.
func (l Log) Print(v ...interface{}) {
l.Msg = fmt.Sprint(v...)
Expand Down
6 changes: 4 additions & 2 deletions zlog_test.go
Expand Up @@ -28,6 +28,9 @@ func TestLog(t *testing.T) {
in func()
want string
}{
// TODO: get line nr. instead of hard-coding it here.
{func() { FieldsLocation().Print("print") }, "INFO: print {location=\"zlog_test.go:32\"}"},

{func() { Print("w00t") }, "INFO: w00t"},
{func() { Printf("w00t %s", "x") }, "INFO: w00t x"},
{func() { Error(errors.New("w00t")) }, "ERROR: w00t\n\ttesting.tRunner\n\t\t/fake/testing.go:42"},
Expand All @@ -39,6 +42,7 @@ func TestLog(t *testing.T) {

{func() { Module("test").Fields(F{"k": "v"}).Print("w00t") }, "test: INFO: w00t {k=\"v\"}"},
{func() { Module("test").Fields(F{"k": 3}).Print("w00t") }, "test: INFO: w00t {k='\\x03'}"},
{func() { Module("test").Fields(F{"k": 3}).Field("k", "1").Print("w00t") }, "test: INFO: w00t {k=\"1\"}"},

{func() { Module("test").Debug("w00t") }, ""},
{func() { SetDebug("xxx").Module("test").Debug("w00t") }, ""},
Expand All @@ -61,8 +65,6 @@ func TestLog(t *testing.T) {
r, _ := http.NewRequest("PUT", "/path?k=v&a=b", nil)
FieldsRequest(r).Error(errors.New("w00t"))
}, "ERROR: w00t {http_form=\"\" http_method=\"PUT\" http_url=\"/path?k=v&a=b\"}\n\ttesting.tRunner\n\t\t/fake/testing.go:42"},

{func() { FieldsLocation().Print("print") }, "INFO: print {location=\"zlog_test.go:65\"}"},
}

for i, tt := range tests {
Expand Down

0 comments on commit 65d5560

Please sign in to comment.