Log with context values as fields.
Compatible with zap, logrus, std logger and testing.T logger.
It supports pkg/errors to add a stack_trace field if the handled error error implements StackTracerinterface.
It offers a convenient way to keep your logs when you are running unit tests.
go get github.com/rockbears/logBy default, it is initialized to wrap logrus package. You can override log.Factory to use the logger library you want.
First register fields
const myField = log.Field("component")
func init() {
log.RegisterField(myField)
}Then add fields as values to you current context.
ctx = context.WithValue(ctx, myField, "myComponent")Finally log as usual.
log.Info(ctx, "this is a log") const myField = log.Field("component")
func init() {
log.RegisterField(myField)
}
func foo(ctx context.Context) {
ctx = context.WithValue(ctx, myField, "myComponent")
log.Info(ctx, "this is a log")
}Preserve your log in unit tests.
func TestFoo(t *testing.T) {
log.Factory = log.NewTestingWrapper(t)
foo(context.TODO())
}Log errors easily.
import "github.com/pkg/errors"
func foo() {
ctx := context.Background()
err := errors.New("this is an error") // from package "github.com/pkg/errors"
log.ErrorWithStackTrace(ctx, err) // will produce a nice stack_trace field
)