hooks/caller: add caller hook for caller info

This commit is contained in:
Simon Eskildsen 2014-12-25 19:49:40 +01:00
parent 51fe59aca1
commit 1b8fbc72c3
3 changed files with 80 additions and 0 deletions

View File

@ -228,6 +228,9 @@ func init() {
* [`github.com/Sirupsen/logrus/hooks/papertrail`](https://github.com/Sirupsen/logrus/blob/master/hooks/papertrail/papertrail.go)
Send errors to the Papertrail hosted logging service via UDP.
* [`github.com/Sirupsen/logrus/hooks/caller`](https://github.com/Sirupsen/logrus/blob/master/hooks/caller)
Include `caller=<file>:<line>` in log entries.
* [`github.com/Sirupsen/logrus/hooks/syslog`](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go)
Send errors to remote syslog server.
Uses standard library `log/syslog` behind the scenes.

36
hooks/caller/caller.go Normal file
View File

@ -0,0 +1,36 @@
package logrus_caller
import (
"github.com/Sirupsen/logrus"
"path/filepath"
"runtime"
"strconv"
"strings"
)
type CallerHook struct {
}
func (hook *CallerHook) Fire(entry *logrus.Entry) error {
entry.Data["caller"] = hook.caller()
return nil
}
func (hook *CallerHook) Levels() []logrus.Level {
return []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
logrus.DebugLevel,
}
}
func (hook *CallerHook) caller() string {
if _, file, line, ok := runtime.Caller(6); ok {
return strings.Join([]string{filepath.Base(file), strconv.Itoa(line)}, ":")
}
// not sure what the convention should be here
return ""
}

View File

@ -0,0 +1,41 @@
package logrus_caller
import (
"bytes"
"encoding/json"
"fmt"
"testing"
"github.com/Sirupsen/logrus"
)
func LogAndAssertJSON(t *testing.T, log func(*logrus.Logger), assertions func(fields logrus.Fields)) {
var buffer bytes.Buffer
var fields logrus.Fields
logger := logrus.New()
logger.Hooks.Add(&CallerHook{})
logger.Out = &buffer
logger.Formatter = new(logrus.JSONFormatter)
log(logger)
err := json.Unmarshal(buffer.Bytes(), &fields)
if err != nil {
t.Error("Error unmarshaling log entry")
}
assertions(fields)
}
func TestCaller(t *testing.T) {
LogAndAssertJSON(t, func(logger *logrus.Logger) {
logger.Info("Hello World")
}, func(fields logrus.Fields) {
expected := "caller_test.go:33"
if fields["caller"] != expected {
t.Error(fmt.Sprintf("Caller was %s, expected %s", fields["caller"], expected))
}
})
}