Skip to content

Latest commit

 

History

History
90 lines (63 loc) · 2.1 KB

README.md

File metadata and controls

90 lines (63 loc) · 2.1 KB

rockbears/log

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.

Install

    go get github.com/rockbears/log

How to use

Global logger

By 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")

Logger instance

You can opt to use a logger instance instead of the global state:

logger := log.NewWithFactory(log.NewLogrusWrapper(logrus.New()))

// Registration is scoped to the logger instance
logger.RegisterField(myField)

logger.Info(ctx, "this is a log")

A typical use case may be to instanciate a logger at app startup and storing it in a struct for use in other methods.

Examples

    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 
    )