log

package module
v2.0.0-...-8764492 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2022 License: Apache-2.0 Imports: 8 Imported by: 0

README

log

Modeled after the repository github.com/go-kit/log to implement Valuer with context

type Valuer func(context.Context) interface{}

Documentation

Overview

Example (Basic)
package main

import (
	"os"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
)

func main() {
	logger := log.NewLogfmtLogger(os.Stdout)
	level.Debug(logger).Log("msg", "this message is at the debug level")
	level.Info(logger).Log("msg", "this message is at the info level")
	level.Warn(logger).Log("msg", "this message is at the warn level")
	level.Error(logger).Log("msg", "this message is at the error level")

}
Output:

level=debug msg="this message is at the debug level"
level=info msg="this message is at the info level"
level=warn msg="this message is at the warn level"
level=error msg="this message is at the error level"
Example (Error)
package main

import (
	"fmt"
	"os"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
	"github.com/pkg/errors"
)

func main() {
	logger := log.NewLogfmtLogger(os.Stdout)
	err := errors.New("noop error")
	errWrap := errors.Wrap(err, "")
	level.Debug(logger).Log("msg", "err", "err", errWrap)
	level.Debug(logger).Log("msg", "err with stacktrace", "err", fmt.Sprintf("%+v", errWrap))

	// level=debug msg=err err=": noop error"
	// level=debug msg="err with stacktrace" err="noop error\ngithub.com/exfly/pkg/log/v2_test.Example_error\n\t/Volumes/code/github.com/exfly/pkg/log/v2/example_test.go:105\ntesting.runExample\n\t/Users/zhf/.goenv/versions/1.16.0/src/testing/run_example.go:63\ntesting.runExamples\n\t/Users/zhf/.goenv/versions/1.16.0/src/testing/example.go:44\ntesting.(*M).Run\n\t/Users/zhf/.goenv/versions/1.16.0/src/testing/testing.go:1419\nmain.main\n\t_testmain.go:57\nruntime.main\n\t/Users/zhf/.goenv/versions/1.16.0/src/runtime/proc.go:225\nruntime.goexit\n\t/Users/zhf/.goenv/versions/1.16.0/src/runtime/asm_amd64.s:1371\n\ngithub.com/exfly/pkg/log/v2_test.Example_error\n\t/Volumes/code/github.com/exfly/pkg/log/v2/example_test.go:106\ntesting.runExample\n\t/Users/zhf/.goenv/versions/1.16.0/src/testing/run_example.go:63\ntesting.runExamples\n\t/Users/zhf/.goenv/versions/1.16.0/src/testing/example.go:44\ntesting.(*M).Run\n\t/Users/zhf/.goenv/versions/1.16.0/src/testing/testing.go:1419\nmain.main\n\t_testmain.go:57\nruntime.main\n\t/Users/zhf/.goenv/versions/1.16.0/src/runtime/proc.go:225\nruntime.goexit\n\t/Users/zhf/.goenv/versions/1.16.0/src/runtime/asm_amd64.s:1371"
}
Output:

Example (Filtered)
package main

import (
	"os"

	logv2 "github.com/exfly/pkg/log/v2"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
	"github.com/pkg/errors"
)

func main() {
	// Set up logger with level filter.
	logger := log.NewLogfmtLogger(os.Stdout)
	logger = level.NewFilter(logger, level.AllowInfo())

	logv2.With(logger).Log("key", "val")

	// Use level helpers to log at different levels.
	logv2.Error(logger).Log("err", errors.New("bad data"))
	logv2.Info(logger).Log("event", "data saved")
	logv2.Debug(logger).Log("next item", 17) // filtered

}
Output:

key=val
level=error err="bad data"
level=info event="data saved"
Example (Term)
package main

import (
	"fmt"
	"os"

	logv2 "github.com/exfly/pkg/log/v2"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
	"github.com/go-kit/log/term"
	"github.com/pkg/errors"
)

func main() {
	colorFn := func(keyvals ...interface{}) term.FgBgColor {
		for i := 0; i < len(keyvals)-1; i += 2 {
			if keyvals[i] != "level" {
				continue
			}

			level, ok := (keyvals[i+1]).(fmt.Stringer)
			if !ok {
				continue
			}

			switch level.String() {
			case "debug":
				return term.FgBgColor{Fg: term.DarkGray}
			case "info":
				return term.FgBgColor{Fg: term.Gray}
			case "warn":
				return term.FgBgColor{Fg: term.Yellow}
			case "error":
				return term.FgBgColor{Fg: term.Red}
			case "crit":
				return term.FgBgColor{Fg: term.Gray, Bg: term.DarkRed}
			default:
				return term.FgBgColor{}
			}
		}
		return term.FgBgColor{}
	}

	logger := term.NewColorLogger(
		term.NewColorWriter(os.Stdout),
		log.NewLogfmtLogger,
		colorFn,
	)

	logger = logv2.With(
		level.NewFilter(logger, level.AllowInfo()),
	)

	logv2.Error(logger).Log("err", errors.New("bad data"))
	logv2.Info(logger).Log("event", "data saved")
	logv2.Debug(logger).Log("next item", 17) // filtered

}
Output:

�[31;1mlevel=error err="bad data"
�[39;49;22m�[37mlevel=info event="data saved"
�[39;49;22m
Example (Zap)
package main

import (
	"os"

	logv2 "github.com/exfly/pkg/log/v2"
	zaplog "github.com/exfly/pkg/log/v2/zap"

	"github.com/go-kit/log/level"
	"github.com/pkg/errors"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func main() {
	var err error

	encoderConfig := zap.NewDevelopmentEncoderConfig()
	// omit zap level time msg
	encoderConfig.LevelKey = zapcore.OmitKey
	encoderConfig.TimeKey = zapcore.OmitKey
	encoderConfig.MessageKey = zapcore.OmitKey

	encoder := zapcore.NewConsoleEncoder(encoderConfig)
	writer := os.Stdout
	zaplogger := zap.New(
		zapcore.NewCore(encoder, zapcore.AddSync(writer), zap.DebugLevel),
		zap.Development(),
		zap.WithCaller(false),
	)
	defer func() { _ = zaplogger.Sync() }()

	logger := level.NewFilter(
		zaplog.NewZapSugarLogger(zaplogger, zapcore.InfoLevel),
		level.AllowAll(),
	)

	err = errors.New("noop error")
	errWrap := errors.Wrap(err, "wrap")
	level.Info(logger).Log(logv2.MsgKey, "has_err", logv2.ErrKey, errWrap)
	level.Debug(logger).Log(logv2.MsgKey, "has_err", logv2.ErrKey, errWrap)
}
Output:

Index

Examples

Constants

View Source
const (
	MsgKey  = "msg"
	ErrKey  = "error"
	NameKey = "name"
)

Variables

View Source
var (
	// DefaultTimestamp is a Valuer that returns the current wallclock time,
	// respecting time zones, when bound.
	DefaultTimestamp = TimestampFormat(time.Now, time.RFC3339Nano)

	// DefaultTimestampUTC is a Valuer that returns the current time in UTC
	// when bound.
	DefaultTimestampUTC = TimestampFormat(
		func() time.Time { return time.Now().UTC() },
		time.RFC3339Nano,
	)

	// DefaultCaller is a Valuer that returns the file and line where the Log
	// method was invoked. It can only be used with log.With.
	DefaultCaller = Caller(3)
)
View Source
var ErrMissingValue = errors.New("(MISSING)")

ErrMissingValue is appended to keyvals slices with odd length to substitute the missing value.

Functions

func Debug

func Debug(logger log.Logger) log.Logger

Debug returns a logger that includes a Key/DebugValue pair.

func Error

func Error(logger log.Logger) log.Logger

Error returns a logger that includes a Key/ErrorValue pair.

func Info

func Info(logger log.Logger) log.Logger

Info returns a logger that includes a Key/InfoValue pair.

func MultiLogger

func MultiLogger(logs ...log.Logger) log.Logger

MultiLogger wraps multi logger.

func Warn

func Warn(logger log.Logger) log.Logger

Warn returns a logger that includes a Key/WarnValue pair.

func With

func With(l log.Logger, kv ...interface{}) log.Logger

With with logger fields.

func WithContext

func WithContext(ctx context.Context, l log.Logger) log.Logger

WithContext returns a shallow copy of l with its context changed to ctx. The provided ctx must be non-nil.

Types

type Valuer

type Valuer func(context.Context) interface{}

A Valuer generates a log value. When passed to With, WithPrefix, or WithSuffix in a value element (odd indexes), it represents a dynamic value which is re-evaluated with each log event.

func Caller

func Caller(depth int) Valuer

Caller returns a Valuer that returns a file and line from a specified depth in the callstack. Users will probably want to use DefaultCaller.

func Timestamp

func Timestamp(t func() time.Time) Valuer

Timestamp returns a timestamp Valuer. It invokes the t function to get the time; unless you are doing something tricky, pass time.Now.

Most users will want to use DefaultTimestamp or DefaultTimestampUTC, which are TimestampFormats that use the RFC3339Nano format.

func TimestampFormat

func TimestampFormat(t func() time.Time, layout string) Valuer

TimestampFormat returns a timestamp Valuer with a custom time format. It invokes the t function to get the time to format; unless you are doing something tricky, pass time.Now. The layout string is passed to Time.Format.

Most users will want to use DefaultTimestamp or DefaultTimestampUTC, which are TimestampFormats that use the RFC3339Nano format.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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