ctxlogrus

package
v0.0.0-...-edc8019 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 9, 2020 License: Apache-2.0 Imports: 4 Imported by: 12

Documentation

Overview

ctxlogrus allows you to store or extract a logrus logger from the context.

When a logger is added to the context (ToContext) its fields are transfered over and will be present when the logger is retrieved later using Export. If a logger is already present on the context you will override it with the new logger passed and override any fields present.

Additional fields can be added to the logger on the context by with the AddFields method.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddFields

func AddFields(ctx context.Context, fields logrus.Fields)

AddFields will add or override fields to context for use when extracting a logger from the context.

Example
package main

import (
	"context"
	"github.com/improbable-eng/go-httpwares/logging/logrus/ctxlogrus"
	"github.com/sirupsen/logrus"
)

func main() {
	ctx := context.Background()
	ctx = ctxlogrus.ToContext(ctx, logrus.WithFields(logrus.Fields{"foo": "bar"}))
	ctxlogrus.AddFields(ctx, logrus.Fields{"num": 42})
}
Output:

func Extract

func Extract(ctx context.Context) *logrus.Entry

Extract takes the logrus.Entry from the context.

The logger will have fields pre-populated that had been present when adding the logger to the context. Fields can also be added using AddFields.

If the has had no logrus.Entry set a no-op logrus.Entry is returned. This makes it safe to use regardless.

Example
package main

import (
	"context"
	"github.com/improbable-eng/go-httpwares/logging/logrus/ctxlogrus"
)

func main() {
	ctx := context.Background()
	entry := ctxlogrus.Extract(ctx)
	entry.Info("logging")
}
Output:

func ToContext

func ToContext(ctx context.Context, entry *logrus.Entry) context.Context

ToContext sets a logrus logger on the context, which can then obtained by Extract. this will override any logger or fields that are already on the context with the logger that has been passed in.

Example
package main

import (
	"context"
	"github.com/improbable-eng/go-httpwares/logging/logrus/ctxlogrus"
	"github.com/sirupsen/logrus"
)

func main() {
	ctx := context.Background()
	ctx = ctxlogrus.ToContext(ctx, logrus.WithFields(logrus.Fields{"foo": "bar"}))
}
Output:

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL