log

package module
v0.0.0-...-2bef83c Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2019 License: MIT Imports: 6 Imported by: 0

README

ZAPFMT

GoDoc Go Report Card CircleCI codecov

ZAP fmt is a small wrapper around Uber log package. This package is supposed to be used with ZAP field functions, so importing zap package is required.

This package provides:

  • An implementation of a key value encoder (instead of JSON).
  • Method for creating a child logger (inheriting attributed) with a different log level.
  • Helper methods for contextualizing a logger by injecting it into a context.Context and latter consuming it directly through it.

Key Value Encoding

Logging using this package will result in the following format.

[ts:2019-04-08T20:21:32.375067Z][level:info][caller:zapfmt/main.go:44][msg:calling thisImportantCall][uuid:34d4fb89-c27b-4c7c-bb51-4e46fba614dd][v:15646231]
[ts:2019-04-08T20:21:32.375073Z][level:debug][caller:zapfmt/main.go:37][msg:calling thisCall][uuid:34d4fb89-c27b-4c7c-bb51-4e46fba614dd][v:3]
[ts:2019-04-08T20:21:32.375079Z][level:error][caller:zapfmt/main.go:44][msg:calling thisImportantCall][uuid:34d4fb89-c27b-4c7c-bb51-4e46fba614dd][v:15646231]

Dynamic Log Level

Instantiating a logger requires a zap.AtomicLevel reference. If you keep the reference to the given object you can then modify the logging level at runtime dynamically. Keep in mind that using the WithLevel method for instantiating a child logger on another level will lock that child logger into the new level.

Zaps AtomicLevel object complies with the ServeHTTP interface, which means that one can hook it directly into a webserver and expose an HTTP method for changing the log level.

Example:

func main() {
    lvl := zap.NewAtomicLevelAt(zap.ErrorLevel)
    logger := log.NewProductionLogger(&lvl)

    // Wrap logger inside given context
    ctx := log.Context(context.Background(), logger)

    go func() {
        for {
            // Use logger within this context to log
            log.Debug(ctx, "my log line", zap.String("key", "value"))
            time.Sleep(1 * time.Second)
        }
    }()

    // Expose dynamic log level endpoint
    http.HandleFunc("/debug/log", lvl)
    http.ListenAndServe(":8080", nil)
}
# Get current log level
curl -X GET http://localhost:8080/debug/log
{"level":"error"}

# Change log level
curl -X PUT http://localhost:8080/debug/log -d '{"level":"debug"}'
{"level":"debug"}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Check

func Check(ctx context.Context, lvl zapcore.Level, msg string) *zapcore.CheckedEntry

Check returns a CheckedEntry if logging a message at the specified level is enabled. It's a completely optional optimization; in high-performance applications, Check can help avoid allocating a slice to hold fields.

func Context

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

Context returns a copy of the parent context in which the logger associated with it is the one given.

Usually you'll call Context with the logger returned by NewProductionLogger. Once you have a context with a logger, all additional logging should be made by using the static methods exported by this package.

func DPanic

func DPanic(ctx context.Context, msg string, fields ...zap.Field)

DPanic logs a message at DPanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

If the logger is in development mode, it then panics (DPanic means "development panic"). This is useful for catching errors that are recoverable, but shouldn't ever happen.

func Debug

func Debug(ctx context.Context, msg string, fields ...zap.Field)

Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func Error

func Error(ctx context.Context, msg string, fields ...zap.Field)

Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func Fatal

func Fatal(ctx context.Context, msg string, fields ...zap.Field)

Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func Info

func Info(ctx context.Context, msg string, fields ...zap.Field)

Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func Named

func Named(ctx context.Context, s string) context.Context

Named adds a new path segment to the logger's name. Segments are joined by periods. By default, Loggers are unnamed.

func Panic

func Panic(ctx context.Context, msg string, fields ...zap.Field)

Panic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then panics, even if logging at PanicLevel is disabled.

func Sugar

func Sugar(ctx context.Context) *zap.SugaredLogger

Sugar wraps the logger to provide a more ergonomic, but slightly slower, API. Sugaring a logger is quite inexpensive, so it's reasonable for a single application to use both Loggers and SugaredLoggers, converting between them on the boundaries of performance-sensitive code.

func Warn

func Warn(ctx context.Context, msg string, fields ...zap.Field)

Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func With

func With(ctx context.Context, fields ...zap.Field) context.Context

With creates a child logger and adds structured context to it. Fields added to the child don't affect the parent, and vice versa.

func WithLevel

func WithLevel(ctx context.Context, lvl zapcore.Level) context.Context

WithLevel created a child logger that logs on the given level. Child logger contains all fields from the parent.

Types

type Logger

type Logger interface {
	// Check returns a CheckedEntry if logging a message at the specified level
	// is enabled. It's a completely optional optimization; in high-performance
	// applications, Check can help avoid allocating a slice to hold fields.
	Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry

	// Named adds a new path segment to the logger's name. Segments are joined by
	// periods. By default, Loggers are unnamed.
	Named(s string) Logger

	// Sugar wraps the logger to provide a more ergonomic, but slightly slower,
	// API. Sugaring a logger is quite inexpensive, so it's reasonable for a
	// single application to use both Loggers and SugaredLoggers, converting
	// between them on the boundaries of performance-sensitive code.
	Sugar() *zap.SugaredLogger

	// With creates a child logger and adds structured context to it. Fields added
	// to the child don't affect the parent, and vice versa.
	With(fields ...zap.Field) Logger

	// WithLevel created a child logger that logs on the given level.
	// Child logger contains all fields from the parent.
	WithLevel(lvl zapcore.Level) Logger

	// DPanic logs a message at DPanicLevel. The message includes any fields
	// passed at the log site, as well as any fields accumulated on the logger.
	DPanic(msg string, fields ...zap.Field)

	// Debug logs a message at DebugLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	Debug(msg string, fields ...zap.Field)

	// Error logs a message at ErrorLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	Error(msg string, fields ...zap.Field)

	// Fatal logs a message at FatalLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	//
	// The logger then calls os.Exit(1), even if logging at FatalLevel is
	// disabled.
	Fatal(msg string, fields ...zap.Field)

	// Info logs a message at InfoLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	Info(msg string, fields ...zap.Field)

	// Panic logs a message at PanicLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	//
	// The logger then panics, even if logging at PanicLevel is disabled.
	Panic(msg string, fields ...zap.Field)

	// Warn logs a message at WarnLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	Warn(msg string, fields ...zap.Field)
}

Logger is the interface that wraps methods needed for a valid logger implementation.

var DefaultLogger Logger = &logger{
	Logger: zap.NewNop(),
}

DefaultLogger is the default logger and is used when given a context with no associated log instance.

DefaultLogger by default discards all logs. You can change it's implementation by settings this variable to an instantiated logger of your own.

func NewProductionLogger

func NewProductionLogger(lvl *zap.AtomicLevel) Logger

NewProductionLogger is a reasonable production logging configuration. Logging is enabled at given level and above. The level can be later adjusted dynamically in runtime by calling SetLevel method.

It uses the custom Key Value encoder, writes to standard error, and enables sampling. Stacktraces are automatically included on logs of ErrorLevel and above.

Directories

Path Synopsis
Package encoders contains custom implementations of zap encoders.
Package encoders contains custom implementations of zap encoders.
examples

Jump to

Keyboard shortcuts

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