log

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 7, 2020 License: BSD-3-Clause Imports: 10 Imported by: 5

Documentation

Overview

Package log provides a wrapped zap logger interface for microservices to use, and also a simple Wrapper interface to be used by other Baseplate.go packages.

Index

Constants

View Source
const DefaultSentryFlushTimeout = time.Second * 2

DefaultSentryFlushTimeout is the timeout used to call sentry.Flush().

View Source
const RFC3339Nano = "ts=2006-01-02T15:04:05.000000Z"

RFC3339Nano is a time format for TimeEncoder

Variables

View Source
var ErrSentryFlushFailed = errors.New("log: sentry flushing failed")

ErrSentryFlushFailed is an error could be returned by the Closer returned by InitSentry, to indicate that the sentry flushing failed.

Functions

func CapitalLevelEncoder

func CapitalLevelEncoder(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder)

CapitalLevelEncoder adds logger level in uppercase

func DPanic

func DPanic(args ...interface{})

DPanic uses fmt.Sprint to construct and log a message.

In development, the logger then panics. (See DPanicLevel for details.)

func DPanicf

func DPanicf(template string, args ...interface{})

DPanicf uses fmt.Sprintf to log a templated message.

In development, the logger then panics. (See DPanicLevel for details.)

func DPanicw

func DPanicw(msg string, keysAndValues ...interface{})

DPanicw logs a message with some additional context.

In development, the logger then panics. (See DPanicLevel for details.)

The variadic key-value pairs are treated as they are in With.

func Debug

func Debug(args ...interface{})

Debug uses fmt.Sprint to construct and log a message.

func Debugf

func Debugf(template string, args ...interface{})

Debugf uses fmt.Sprintf to log a templated message.

func Debugw

func Debugw(msg string, keysAndValues ...interface{})

Debugw logs a message with some additional context.

The variadic key-value pairs are treated as they are in With.

When debug-level logging is disabled, this is much faster than

With(keysAndValues).Debug(msg)

func Error

func Error(args ...interface{})

Error uses fmt.Sprint to construct and log a message.

func ErrorWithSentry

func ErrorWithSentry(ctx context.Context, msg string, err error, keysAndValues ...interface{})

ErrorWithSentry logs a message with some additional context, then sends the error to Sentry.

The variadic key-value pairs are treated as they are in With.

If a sentry hub is attached to the context object passed in (it will be if the context object is from baseplate hooked request context), that hub will be used to do the reporting. Otherwise the global sentry hub will be used instead.

func Errorf

func Errorf(template string, args ...interface{})

Errorf uses fmt.Sprintf to log a templated message.

func Errorw

func Errorw(msg string, keysAndValues ...interface{})

Errorw logs a message with some additional context.

The variadic key-value pairs are treated as they are in With.

func Fatal

func Fatal(args ...interface{})

Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit.

func Fatalf

func Fatalf(template string, args ...interface{})

Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit.

func Fatalw

func Fatalw(msg string, keysAndValues ...interface{})

Fatalw logs a message with some additional context, then calls os.Exit.

The variadic key-value pairs are treated as they are in With.

func FullCallerEncoder

func FullCallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder)

FullCallerEncoder serializes a caller in /full/path/to/package/file:line format.

func Info

func Info(args ...interface{})

Info uses fmt.Sprint to construct and log a message.

func Infof

func Infof(template string, args ...interface{})

Infof uses fmt.Sprintf to log a templated message.

func Infow

func Infow(msg string, keysAndValues ...interface{})

Infow logs a message with some additional context.

The variadic key-value pairs are treated as they are in With.

func InitFromConfig

func InitFromConfig(cfg Config)

InitFromConfig initializes the log package using the given Config and JSON logger.

func InitLogger

func InitLogger(logLevel Level)

InitLogger provides a quick way to start or replace a logger.

func InitLoggerJSON

func InitLoggerJSON(logLevel Level)

InitLoggerJSON initializes global logger with full json format.

The JSON format is also compatible with logdna's ingestion format: https://docs.logdna.com/docs/ingestion

func InitLoggerWithConfig

func InitLoggerWithConfig(logLevel Level, cfg zap.Config) error

InitLoggerWithConfig provides a quick way to start or replace a logger.

Pass in a cfg to provide a logger with custom setting

func InitSentry

func InitSentry(cfg SentryConfig) (io.Closer, error)

InitSentry initializes sentry reporting.

The io.Closer returned calls sentry.Flush with SentryFlushTimeout. If it returns an error, that error is guaranteed to wrap ErrSentryFlushFailed.

You can also just call sentry.Init, which provides even more customizations. This function is provided to do the customizations we care about the most, and to provide a Closer to be more consistent with other baseplate packages.

func JSONTimeEncoder

func JSONTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

JSONTimeEncoder encodes time in RFC3339Nano without extra information.

It's suitable to be used in the full JSON format.

func NopWrapper

func NopWrapper(msg string)

NopWrapper is a Wrapper implementation that does nothing.

func Panic

func Panic(args ...interface{})

Panic uses fmt.Sprint to construct and log a message, then panics.

func Panicf

func Panicf(template string, args ...interface{})

Panicf uses fmt.Sprintf to log a templated message, then panics.

func Panicw

func Panicw(msg string, keysAndValues ...interface{})

Panicw logs a message with some additional context, then panics.

The variadic key-value pairs are treated as they are in With.

func ShortCallerEncoder

func ShortCallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder)

ShortCallerEncoder serializes a caller in package/file:line format, trimming all but the final directory from the full path.

func Sync

func Sync() error

Sync flushes any buffered log entries.

func TimeEncoder

func TimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

TimeEncoder is customized to add ts in the front

func Warn

func Warn(args ...interface{})

Warn uses fmt.Sprint to construct and log a message.

func Warnf

func Warnf(template string, args ...interface{})

Warnf uses fmt.Sprintf to log a templated message.

func Warnw

func Warnw(msg string, keysAndValues ...interface{})

Warnw logs a message with some additional context.

The variadic key-value pairs are treated as they are in With.

func With

func With(args ...interface{}) *zap.SugaredLogger

With wraps around the underline logger's With.

Types

type Config

type Config struct {
	// Level is the log level you want to set your service to.
	Level Level `yaml:"level"`
}

Config is the confuration struct for the log package.

Can be deserialized from YAML.

type KitWrapper

type KitWrapper zapcore.Level

KitWrapper is a type that implements go-kit/log.Logger interface with zap logger.

func KitLogger

func KitLogger(level Level) KitWrapper

KitLogger returns a go-kit compatible logger.

func (KitWrapper) Log

func (w KitWrapper) Log(keyvals ...interface{}) error

Log implements go-kit/log.Logger interface.

type Level

type Level string

Level is the verbose representation of log level

const (
	NopLevel   Level = "nop"
	DebugLevel Level = "debug"
	InfoLevel  Level = "info"
	WarnLevel  Level = "warn"
	ErrorLevel Level = "error"
	PanicLevel Level = "panic"
	FatalLevel Level = "fatal"

	// This will have the same effect as nop but slower
	ZapNopLevel zapcore.Level = zapcore.FatalLevel + 1
)

Enums for Level

func (Level) ToZapLevel

func (l Level) ToZapLevel() zapcore.Level

ToZapLevel converts Level to a zap acceptable atomic level struct

type SentryConfig

type SentryConfig struct {
	// The Sentry DSN to use.
	// If empty, SENTRY_DSN environment variable will be used instead.
	// If that's also empty, then all sentry operations will be nop.
	DSN string

	// SampleRate between 0 and 1, default is 1.
	SampleRate *float64

	// The name of your service.
	ServerName string

	// An environment string like "prod", "staging".
	Environment string

	// List of regexp strings that will be used to match against event's message
	// and if applicable, caught errors type and value.
	// If the match is found, then a whole event will be dropped.
	IgnoreErrors []string

	// FlushTimeout is the timeout to be used to call sentry.Flush when closing
	// the Closer returned by InitSentry.
	// If <=0, DefaultSentryFlushTimeout will be used.
	FlushTimeout time.Duration
}

SentryConfig is the config to be passed into InitSentry.

All fields are optional.

type Wrapper

type Wrapper func(msg string)

Wrapper defines a simple interface to wrap logging functions.

As principles, library code should

1. Not do any logging. The library code should communicate errors back to the caller, and let the caller decide how to deal with them (log them, ignore them, panic, etc.)

2. In some rare cases, 1 is not possible, for example the error might happen in a background goroutine. In those cases some logging is necessary, but those should be kept at minimal, and the library code should provide control to the caller on how to do those logging.

This interface is meant to solve Principle 2 above. In reality we might actually use different logging libraries in different services, and they are not always compatible with each other. Wrapper is a simple common ground that it's easy to wrap whatever logging library we use into.

With that in mind, this interface should only be used by library code, when the case satisfies all of the following 3 criteria:

1. A bad thing happened.

2. This is unexpected. For expected errors, the library should either handle it by itself (e.g. retry), or communicate it back to the caller and let them handle it.

3. This is also recoverable. Unrecoverable errors should also be communicated back to the caller to handle.

Baseplate services should use direct logging functions for their logging needs, instead of using Wrapper interface.

For production code using baseplate libraries, Baseplate services should use ErrorWithSentryWrapper in most cases, as whenever the Wrapper is called that's something bad and unexpected happened and the service owner should be aware of. Non-Baseplate services should use error level in whatever logging library they use.

For unit tests of library code using Wrapper, TestWrapper is provided that would fail the test when Wrapper is called.

Additionally, this interface is also compatible with thrift.Logger and can be used interchangeably (sometimes a typecasting is needed).

func ErrorWithSentryWrapper

func ErrorWithSentryWrapper() Wrapper

ErrorWithSentryWrapper is a Wrapper implementation that both use Zap logger to log at error level, and also send the message to Sentry.

In most cases this should be the one used to pass into Baseplate.go libraries expecting a log.Wrapper. If the service didn't configure sentry, then this wrapper is essentially the same as log.ZapWrapper(log.ErrorLevel).

Note that this should not be used as the logger set into thrift.TSimpleServer, as that would use the logger to log network I/O errors, which would be too spammy to be sent to Sentry. For this reason, it's returning a Wrapper instead of being a Wrapper itself, thus forcing an extra typecasting to be used as a thrift.Logger.

func FallbackWrapper

func FallbackWrapper(logger Wrapper) Wrapper

FallbackWrapper is the nil-safe wrapper.

It returns NopWrapper when logger is nil, otherwise it return logger as-is.

func StdWrapper

func StdWrapper(logger *stdlog.Logger) Wrapper

StdWrapper wraps stdlib log package into a Wrapper.

func TestWrapper

func TestWrapper(tb testing.TB) Wrapper

TestWrapper is a wrapper can be used in test codes.

It fails the test when called.

func ZapWrapper

func ZapWrapper(level Level) Wrapper

ZapWrapper wraps zap log package into a Wrapper.

Jump to

Keyboard shortcuts

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