log

package
v3.9.0-rc3 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2020 License: Apache-2.0 Imports: 10 Imported by: 7

Documentation

Overview

Package log contains all the structs to log TTN.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ColorFromTerm = func(handler *CLIHandler) {
	COLORTERM := os.Getenv("COLORTERM")
	TERM := os.Getenv("TERM")

	color := COLORTERM != ""

	for _, substring := range colorTerms {
		color = color || strings.Contains(TERM, substring)
	}

	color = color && COLORTERM != "0"

	if out, ok := handler.Writer.(*os.File); ok {

		color = color && (isatty.IsTerminal(out.Fd()) || isatty.IsCygwinTerminal(out.Fd()))
	}

	handler.UseColor = color
}

ColorFromTerm determines from the TERM and COLORTERM environment variables wether or not to use colors. If set, colors will be enabled in these cases: - COLORTERM is set and has a value different from 0 - TERM contains the substring "xterm" or "color" and COLORTERM is not 0

View Source
var Colors = [...]int{
	DebugLevel: gray,
	InfoLevel:  blue,
	WarnLevel:  yellow,
	ErrorLevel: red,
	FatalLevel: red,
}

Colors mapping.

View Source
var Default = NewLogger()

Default is the default logger used for the package global logging functions

View Source
var ErrInvalidLevel = errors.New("Invalid log level")

ErrInvalidLevel indicates an invalid log level

View Source
var Noop = &noop{}

Noop just does nothing.

View Source
var NoopHandler = &noopHandler{}

NoopHandler is a handler that does nothing.

Functions

func Debug

func Debug(msg string)

Debug calls Default.Debug

func Debugf

func Debugf(msg string, v ...interface{})

Debugf calls Default.Debugf

func Error

func Error(msg string)

Error calls Default.Error

func Errorf

func Errorf(msg string, v ...interface{})

Errorf calls Default.Errorf

func Fatal

func Fatal(msg string)

Fatal calls Default.Fatal

func Fatalf

func Fatalf(msg string, v ...interface{})

Fatalf calls Default.Fatalf

func Info

func Info(msg string)

Info calls Default.Info

func Infof

func Infof(msg string, v ...interface{})

Infof calls Default.Infof

func NewContext

func NewContext(ctx context.Context, logger Interface) context.Context

NewContext returns a derived context with the logger set.

func NewContextWithField

func NewContextWithField(ctx context.Context, k string, v interface{}) context.Context

NewContextWithField returns a derived context with the given field added to the logger.

func NewContextWithFields

func NewContextWithFields(ctx context.Context, f Fielder) context.Context

NewContextWithFields returns a derived context with the given fields added to the logger.

func Warn

func Warn(msg string)

Warn calls Default.Warn

func Warnf

func Warnf(msg string, v ...interface{})

Warnf calls Default.Warnf

Types

type CLIHandler

type CLIHandler struct {
	Writer   io.Writer
	UseColor bool
	// contains filtered or unexported fields
}

CLIHandler implements Handler.

func NewCLI

func NewCLI(w io.Writer, opts ...CLIHandlerOption) *CLIHandler

NewCLI returns a new CLIHandler.

func (*CLIHandler) HandleLog

func (h *CLIHandler) HandleLog(e Entry) error

HandleLog implements Handler.

type CLIHandlerOption

type CLIHandlerOption func(*CLIHandler)

CLIHandlerOption is the type of options for the CLIHandler.

func UseColor

func UseColor(arg bool) CLIHandlerOption

UseColor is a functional option with which you can force the usage of colors on or off.

type Entry

type Entry interface {
	Level() Level
	Fields() Fielder
	Message() string
	Timestamp() time.Time
}

Entry is the interface of log entries.

type F

type F struct {
	// contains filtered or unexported fields
}

F is a Fielder that uses structural sharing to avoid copying entries. Setting a key is O(1), getting a key is O(n) (where n is the number of entries), but we only use this to accumulate fields so that's ok.

func Fields

func Fields(pairs ...interface{}) *F

Fields returns a new immutable fields structure.

func (*F) Fields

func (f *F) Fields() map[string]interface{}

Fields implements Fielder. Returns all fields in O(n), where n is the number of entries in the map.

func (*F) Get

func (f *F) Get(key string) (interface{}, bool)

Get returns the key from the fields in O(n), where n is the number of entries.

func (*F) With

func (f *F) With(nodes map[string]interface{}) *F

With returns a new F that has the fields in nodes.

func (*F) WithError

func (f *F) WithError(err error) *F

WithError returns new fields that contain the passed error and all its fields (if any).

func (*F) WithField

func (f *F) WithField(name string, val interface{}) *F

WithField returns a new fielder that has the key set to value.

func (*F) WithFields

func (f *F) WithFields(fields Fielder) *F

WithFields returns a new fielder that has all the fields of the other fielder.

type Fielder

type Fielder interface {
	Fields() map[string]interface{}
}

Fielder is the interface for anything that can have fields.

type Handler

type Handler interface {
	HandleLog(Entry) error
}

Handler is the interface of things that can handle log entries.

type HandlerFunc

type HandlerFunc func(Entry) error

HandlerFunc is a function that implements Handler.

func (HandlerFunc) HandleLog

func (fn HandlerFunc) HandleLog(e Entry) error

HandleLog implements Handler.

type Interface

type Interface interface {
	Debug(msg string)
	Info(msg string)
	Warn(msg string)
	Error(msg string)
	Fatal(msg string)
	Debugf(msg string, v ...interface{})
	Infof(msg string, v ...interface{})
	Warnf(msg string, v ...interface{})
	Errorf(msg string, v ...interface{})
	Fatalf(msg string, v ...interface{})
	WithField(string, interface{}) Interface
	WithFields(Fielder) Interface
	WithError(error) Interface
}

Interface is the interface for logging TTN.

func FromContext

func FromContext(ctx context.Context) Interface

FromContext returns the logger that is attached to the context or returns the Noop logger if it does not exist

func WithError

func WithError(err error) Interface

WithError calls Default.WithError

func WithField

func WithField(k string, v interface{}) Interface

WithField calls Default.WithField

func WithFields

func WithFields(f Fielder) Interface

WithFields calls Default.WithFields

type Level

type Level int8

Level is the level of logging.

const (

	// DebugLevel is the log level for debug messages, usually turned of in production.
	DebugLevel Level

	// InfoLevel is the log level for informational messages.
	InfoLevel

	// WarnLevel is the log level for warnings.
	// Warnings are more important than info but do not need individual human review.
	WarnLevel

	// ErrorLevel is the log level for high priority error messages.
	// When everything is running smoothly, an application should not be logging error level messages.
	ErrorLevel

	// FatalLevel the log level for unrecoverable errors.
	// Using this level will exit the program.
	FatalLevel
)

func ParseLevel

func ParseLevel(str string) (Level, error)

ParseLevel parses a string into a log level or returns an error otherwise.

func (Level) MarshalText

func (l Level) MarshalText() ([]byte, error)

MarshalText implments encoding.TextMarshaller.

func (Level) String

func (l Level) String() string

String implements fmt.Stringer.

func (*Level) UnmarshalConfigString

func (l *Level) UnmarshalConfigString(str string) error

UnmarshalConfigString implements config.Configurable.

func (*Level) UnmarshalText

func (l *Level) UnmarshalText(text []byte) error

UnmarshalText implments encoding.TextMarshaller.

type Logger

type Logger struct {
	Level   Level
	Handler Handler
	// contains filtered or unexported fields
}

Logger implements Stack.

func NewLogger

func NewLogger(opts ...Option) *Logger

NewLogger creates a new logger with the default options.

func (*Logger) Debug

func (l *Logger) Debug(msg string)

Debug implements log.Interface.

func (*Logger) Debugf

func (l *Logger) Debugf(msg string, v ...interface{})

Debugf implements log.Interface.

func (*Logger) Error

func (l *Logger) Error(msg string)

Error implements log.Interface.

func (*Logger) Errorf

func (l *Logger) Errorf(msg string, v ...interface{})

Errorf implements log.Interface.

func (*Logger) Fatal

func (l *Logger) Fatal(msg string)

Fatal implements log.Interface.

func (*Logger) Fatalf

func (l *Logger) Fatalf(msg string, v ...interface{})

Fatalf implements log.Interface.

func (*Logger) Info

func (l *Logger) Info(msg string)

Info implements log.Interface.

func (*Logger) Infof

func (l *Logger) Infof(msg string, v ...interface{})

Infof implements log.Interface.

func (*Logger) Use

func (l *Logger) Use(middleware Middleware)

Use installs the handler middleware.

func (*Logger) Warn

func (l *Logger) Warn(msg string)

Warn implements log.Interface.

func (*Logger) Warnf

func (l *Logger) Warnf(msg string, v ...interface{})

Warnf implements log.Interface.

func (*Logger) WithError

func (l *Logger) WithError(err error) Interface

WithError implements log.Interface.

func (*Logger) WithField

func (l *Logger) WithField(name string, val interface{}) Interface

WithField implements log.Interface.

func (*Logger) WithFields

func (l *Logger) WithFields(fields Fielder) Interface

WithFields implements log.Interface.

type Middleware

type Middleware interface {
	// Wrap decorates the next handler by doing some extra work.
	Wrap(next Handler) Handler
}

Middleware is the interface of middleware for handlers. It's similar to middleware in HTTP stacks, where the middleware gets access to the entry being logged and the next handler in the stack.

Example
// build our custom handler (needed for example tests, because it expects us to use fmt.Println)
handler := HandlerFunc(func(entry Entry) error {
	fmt.Printf("%s: %s\n", strings.ToUpper(entry.Level().String()), entry.Message())
	return nil
})

logger := NewLogger(WithHandler(handler), WithLevel(InfoLevel))

// printer is a middleware that prints the strings be
printer := MiddlewareFunc(func(next Handler) Handler {
	return HandlerFunc(func(entry Entry) error {
		fmt.Println("== Before ==")
		err := next.HandleLog(entry)
		fmt.Println("== After ==")

		return err
	})
})

messages := 0

// counter is a middleware that counts the messages
counter := MiddlewareFunc(func(next Handler) Handler {
	return HandlerFunc(func(entry Entry) error {
		messages++
		return next.HandleLog(entry)
	})
})

logger.Use(printer)
logger.Use(counter)

logger.Info("Hey!")
fmt.Println("Number of messages:", messages)
Output:

== Before ==
INFO: Hey!
== After ==
Number of messages: 1

type MiddlewareFunc

type MiddlewareFunc func(next Handler) Handler

MiddlewareFunc is a function that implements Middleware.

func (MiddlewareFunc) Wrap

func (fn MiddlewareFunc) Wrap(next Handler) Handler

Wrap implements Middleware.

type Option

type Option func(*Logger)

Option for the logger

func WithHandler

func WithHandler(handler Handler) Option

WithHandler sets the handler on the logger.

func WithLevel

func WithLevel(level Level) Option

WithLevel sets the level on the logger.

type Stack

type Stack interface {
	// Log is an Interface.
	Interface

	// Use installs the specified middleware in the middleware stack.
	Use(Middleware)
}

Stack is the interface of loggers that have a handler stack with middleware.

Directories

Path Synopsis
handler
memory
Package memory implements a pkg/log.Handler that saves all entries in process memory
Package memory implements a pkg/log.Handler that saves all entries in process memory
multi
Package multi implements a pkg/log.Handler that applies every log message on multiple Handlers
Package multi implements a pkg/log.Handler that applies every log message on multiple Handlers
middleware
observability
Package observability implements a pkg/log.Handler that exports metrics for the logged messages.
Package observability implements a pkg/log.Handler that exports metrics for the logged messages.
sentry
Package sentry implements a pkg/log.Handler that sends errors to Sentry
Package sentry implements a pkg/log.Handler that sends errors to Sentry
Package test exposes simple implementations of log interfaces that can be used for testing.
Package test exposes simple implementations of log interfaces that can be used for testing.

Jump to

Keyboard shortcuts

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