log

package module
Version: v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2019 License: MIT Imports: 16 Imported by: 0

README

Deprecated

The development of this library is discontinued and we encourage you to avoid using it in new projects. There are better alternatives out there.

logging

Simple logging package in Go used at Cabify. Originally forked from cenkalti/log

GoDoc

Install

$ go get github.com/cabify/go-logging

Features

  • Log levels (DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL)
  • Different colored output for different log levels
  • Customizable logging handlers
  • Customizable formatters
  • Log to multiple backends concurrently

Example Usage

See https://github.com/cabify/go-logging/blob/master/example/example.go

Documentation

Overview

Package log is an alternative to log package in standard library.

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultLogger    Logger    = NewLogger(procName)
	DefaultLevel     Level     = INFO
	DefaultHandler   Handler   = NewFileHandler(os.Stderr)
	DefaultFormatter Formatter = defaultFormatter{}
)
View Source
var BaggageContextKey interface{} = "logctx-data-map-string-interface"

BaggageContextKey is the key to be used for the baggage map[string]interface{} in context.*Value. It's intentionally a public string type, so the deprecation of this library is easier, since a public string type can be defined in another package

View Source
var LevelColors = map[Level]Color{
	CRITICAL: MAGENTA,
	ERROR:    RED,
	WARNING:  YELLOW,
	NOTICE:   GREEN,
	INFO:     NOCOLOR,
	DEBUG:    BLUE,
}
View Source
var LevelNames = map[Level]string{
	CRITICAL: "CRITICAL",
	ERROR:    "ERROR",
	WARNING:  "WARNING",
	NOTICE:   "NOTICE",
	INFO:     "INFO",
	DEBUG:    "DEBUG",
}

Functions

func Baggage added in v1.4.0

func Baggage(ctx context.Context) map[string]interface{}

Baggage is a handy helper to extract the baggage from the context, probably to be used with another logger

func ConfigureDefaultLogger added in v1.2.0

func ConfigureDefaultLogger(name string, cfg Config, logCounters ...CountLogMessage)

ConfigureDefaultLogger configures loggers for your service, optionally adding log message counters with your favorite metrics system

func Critical

func Critical(args ...interface{})

func Criticalf

func Criticalf(format string, args ...interface{})

func Criticalln

func Criticalln(args ...interface{})

func Debug

func Debug(args ...interface{})

func Debugf

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

func Debugln

func Debugln(args ...interface{})

func Error

func Error(args ...interface{})

func Errorf

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

func Errorln

func Errorln(args ...interface{})

func Fatal

func Fatal(args ...interface{})

func Fatalf

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

func Fatalln

func Fatalln(args ...interface{})

func Info

func Info(args ...interface{})

func Infof

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

func Infoln

func Infoln(args ...interface{})

func NewContextFromWithValue

func NewContextFromWithValue(ctx context.Context, k, v string) context.Context

NewContextFromWithValue creates a new context with baggage values from ctx plus the provided one it's just a shorthand for the composition of NewContextWithBaggageFrom and WithBaggageValue

func NewContextWithBaggageFrom

func NewContextWithBaggageFrom(ctx context.Context) context.Context

NewContextWithBaggageFrom returns a new context with baggage values obtained from another context

func NewID

func NewID() string

NewID returns a random id to follow the log traces

func Notice

func Notice(args ...interface{})

func Noticef

func Noticef(format string, args ...interface{})

func Noticeln

func Noticeln(args ...interface{})

func Panic

func Panic(args ...interface{})

func Panicf

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

func Panicln

func Panicln(args ...interface{})

func SetLevel

func SetLevel(l Level)

SetLevel changes the level of DefaultLogger and DefaultHandler.

func Warning

func Warning(args ...interface{})

func Warningf

func Warningf(format string, args ...interface{})

func Warningln

func Warningln(args ...interface{})

func WithBaggageValue

func WithBaggageValue(ctx context.Context, key, value string) context.Context

WithBaggageValue returns a context with the added key value pair in the baggage store.

func WithBaggageValues

func WithBaggageValues(ctx context.Context, keyValue map[string]string) context.Context

WithBaggageValues returns a context with all key value pairs added to the baggage store.

Types

type BaseHandler

type BaseHandler struct {
	Level     Level
	Formatter Formatter
}

func NewBaseHandler

func NewBaseHandler() *BaseHandler

func (*BaseHandler) FilterAndFormat

func (h *BaseHandler) FilterAndFormat(rec *Record) string

func (*BaseHandler) SetFormatter

func (h *BaseHandler) SetFormatter(f Formatter)

func (*BaseHandler) SetLevel

func (h *BaseHandler) SetLevel(l Level)

type Color

type Color int
const (
	BLACK Color = iota + 30
	RED
	GREEN
	YELLOW
	BLUE
	MAGENTA
	CYAN
	WHITE
	NOCOLOR = -1
)

Colors for different log levels.

type Config added in v1.2.0

type Config struct {
	Level  string `default:"info"`
	Output string `default:"stdout"`
}

Config defines the logging configuration

type CountLogMessage added in v1.2.0

type CountLogMessage func(level string)

CountLogMessage offers a method to count log messages logged by the logger

type Factory

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

Factory provides context aware loggers.

func NewFactory

func NewFactory() Factory

NewFactory instantiates a factory with the default logger.

func (Factory) For

func (f Factory) For(ctx context.Context) Logger

For provides a logger which is aware of the passed context and will prepend the context baggage values.

type FileHandler

type FileHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

FileHandler is a handler implementation that writes the logging output to a *os.File. If given file is a tty, output will be colored.

func NewFileHandler

func NewFileHandler(f *os.File) *FileHandler

func (*FileHandler) Close

func (h *FileHandler) Close() error

func (*FileHandler) Handle

func (h *FileHandler) Handle(rec *Record)

type Formatter

type Formatter interface {
	// Format the record and return a message.
	Format(*Record) (message string)
}

Formatter formats a record.

type Handler

type Handler interface {
	SetFormatter(Formatter)
	SetLevel(Level)
	// Handle single log record.
	Handle(*Record)
	// Close the handler.
	Close() error
}

Handler handles the output.

type Level

type Level int
const (
	CRITICAL Level = iota
	ERROR
	WARNING
	NOTICE
	INFO
	DEBUG
)

Logging levels.

func (*Level) Decode added in v1.3.0

func (l *Level) Decode(val string) error

Decode fills this level from the given input string. This makes `Level` implement the `Decoder` interface of `envconfig` library, so it can be used in config types seamlessly.

type Logger

type Logger interface {
	// SetLevel changes the level of the logger. Default is logging.Info.
	SetLevel(Level)

	// SetHandler replaces the current handler for output. Default is logging.StderrHandler.
	SetHandler(Handler)

	// SetCallDepth sets the parameter passed to runtime.Caller().
	// It is used to get the file name from call stack.
	// For example you need to set it to 1 if you are using a wrapper around
	// the Logger. Default value is zero.
	SetCallDepth(int)

	// Fatal is equivalent to Logger.Critical followed by a call to os.Exit(1).
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
	Fatalln(args ...interface{})
	// Panic is equivalent to Logger.Critical followed by a call to panic().
	Panic(args ...interface{})
	Panicf(format string, args ...interface{})
	Panicln(args ...interface{})

	// Log functions
	Critical(args ...interface{})
	Criticalf(format string, args ...interface{})
	Criticalln(args ...interface{})
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Errorln(args ...interface{})
	Warning(args ...interface{})
	Warningf(format string, args ...interface{})
	Warningln(args ...interface{})
	Notice(args ...interface{})
	Noticef(format string, args ...interface{})
	Noticeln(args ...interface{})
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Infoln(args ...interface{})
	Debug(args ...interface{})
	Debugf(format string, args ...interface{})
	Debugln(args ...interface{})
}

Logger is the interface for outputing log messages in different levels. A new Logger can be created with NewLogger() function. You can changed the output handler with SetHandler() function.

func For

func For(ctx context.Context) Logger

For provides a logger which is aware of the passed context and will prepend the context baggage values, using DefaultLogger as base logger.

func NewLogger

func NewLogger(name string) Logger

NewLogger returns a new Logger implementation. Do not forget to close it at exit.

type LoggerFactory added in v1.5.0

type LoggerFactory interface {
	For(ctx context.Context) Logger
}

LoggerFactory creates Logger instances

var DefaultFactory LoggerFactory = NewFactory()

DefaultFactory is the factory used to create new loggers

type MultiHandler

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

MultiHandler sends the log output to multiple handlers concurrently.

func NewMultiHandler

func NewMultiHandler(handlers ...Handler) *MultiHandler

func (*MultiHandler) Close

func (b *MultiHandler) Close() error

func (*MultiHandler) Handle

func (b *MultiHandler) Handle(rec *Record)

func (*MultiHandler) SetFormatter

func (b *MultiHandler) SetFormatter(f Formatter)

func (*MultiHandler) SetLevel

func (b *MultiHandler) SetLevel(l Level)

type NoDebugLogger

type NoDebugLogger struct {
	Logger
}

NoDebugLogger embeds a Logger, but in calls to debug functions it does nothing. It avoids doing fmt.Sprintf() for those calls as they will be discarded anyways. This makes those calls like 50 times faster (see benchmark file)

func (NoDebugLogger) Debug

func (NoDebugLogger) Debug(args ...interface{})

func (NoDebugLogger) Debugf

func (NoDebugLogger) Debugf(format string, args ...interface{})

func (NoDebugLogger) Debugln

func (NoDebugLogger) Debugln(args ...interface{})

type Record

type Record struct {
	Message     string    // Formatted log message
	LoggerName  string    // Name of the logger module
	Level       Level     // Level of the record
	Time        time.Time // Time of the record (local time)
	Filename    string    // File name of the log call (absolute path)
	Line        int       // Line number in file
	ProcessID   int       // PID
	ProcessName string    // Name of the process
}

Record contains all of the information about a single log message.

type SyslogHandler

type SyslogHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

SyslogHandler sends the logging output to syslog.

func NewSyslogHandler

func NewSyslogHandler(tag string) (*SyslogHandler, error)

func NewSyslogHandlerDial

func NewSyslogHandlerDial(network, raddr, tag string) (*SyslogHandler, error)

func (*SyslogHandler) Close

func (b *SyslogHandler) Close() error

func (*SyslogHandler) Handle

func (b *SyslogHandler) Handle(rec *Record)

type WriterHandler

type WriterHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

WriterHandler is a handler implementation that writes the logging output to a io.Writer.

func NewWriterHandler

func NewWriterHandler(w io.Writer) *WriterHandler

func (*WriterHandler) Close

func (b *WriterHandler) Close() error

func (*WriterHandler) Handle

func (b *WriterHandler) Handle(rec *Record)

Directories

Path Synopsis
Package logtest is intended to be used by tests for checking that baggage values have been correctly set
Package logtest is intended to be used by tests for checking that baggage values have been correctly set

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL