logger

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2020 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

  Package logger contains filters and handles for the logging utilities in Revel.
  These facilities all currently use the logging library called log15 at
  https://github.com/inconshreveable/log15

	Defining handlers happens as follows
	1) ALL handlers (log.all.output) replace any existing handlers
	2) Output handlers (log.error.output) replace any existing handlers
	3) Filter handlers (log.xxx.filter, log.xxx.nfilter) append to existing handlers,
	   note log.all.filter is treated as a filter handler, so it will NOT replace existing ones

Index

Constants

View Source
const (
	// The test mode flag overrides the default log level and shows only errors
	TEST_MODE_FLAG = "testModeFlag"
	// The special use flag enables showing messages when the logger is setup
	SPECIAL_USE_FLAG = "specialUseFlag"
)

Variables

View Source
var LogFunctionMap = map[string]func(*CompositeMultiHandler, *LogOptions){

	"off": func(c *CompositeMultiHandler, logOptions *LogOptions) {

		if logOptions.HandlerWrap != nil {
			for _, l := range logOptions.Levels {
				c.SetHandler(logOptions.HandlerWrap.SetChild(NilHandler()), logOptions.ReplaceExistingHandler, l)
			}
		} else {

			c.SetHandlers(NilHandler(), logOptions)
		}
	},

	"": func(*CompositeMultiHandler, *LogOptions) {},

	"stdout": func(c *CompositeMultiHandler, logOptions *LogOptions) {
		if logOptions.Ctx != nil {
			logOptions.SetExtendedOptions(
				"noColor", !logOptions.Ctx.BoolDefault("log.colorize", true),
				"smallDate", logOptions.Ctx.BoolDefault("log.smallDate", true))
		}
		c.SetTerminal(os.Stdout, logOptions)
	},

	"stderr": func(c *CompositeMultiHandler, logOptions *LogOptions) {
		c.SetTerminal(os.Stderr, logOptions)
	},
}

The log function map can be added to, so that you can specify your own logging mechanism it has defaults for off, stdout, stderr

A list of all the log levels

Functions

func GetLogger

func GetLogger(name string, logger MultiLogger) (l *log.Logger)

Returns the logger for the name

func NewCallStack

func NewCallStack() interface{}

For logging purposes the call stack can be used to record the stack trace of a bad error simply pass it as a context field in your log statement like `controller.Log.Crit("This should not occur","stack",revel.NewCallStack())`

func NewCompositeMultiHandler

func NewCompositeMultiHandler() (*CompositeMultiHandler, LogHandler)

func SetDefaultLog

func SetDefaultLog(fromLog MultiLogger)

Set the systems default logger Default logs will be captured and handled by revel at level info

Types

type CallStack added in v0.20.0

type CallStack interface {
	fmt.Formatter // Requirement
}

Currently the only requirement for the callstack is to support the Formatter method which stack.Call does so we use that

type CompositeMultiHandler

type CompositeMultiHandler struct {
	DebugHandler    LogHandler
	InfoHandler     LogHandler
	WarnHandler     LogHandler
	ErrorHandler    LogHandler
	CriticalHandler LogHandler
}

func InitializeFromConfig

func InitializeFromConfig(basePath string, config *config.Context) (c *CompositeMultiHandler)

func (*CompositeMultiHandler) Disable

func (h *CompositeMultiHandler) Disable(levels ...LogLevel)

func (*CompositeMultiHandler) Log

func (h *CompositeMultiHandler) Log(r *Record) (err error)

func (*CompositeMultiHandler) SetHandler

func (h *CompositeMultiHandler) SetHandler(handler LogHandler, replace bool, level LogLevel)

func (*CompositeMultiHandler) SetHandlers

func (h *CompositeMultiHandler) SetHandlers(handler LogHandler, options *LogOptions)

For the multi handler set the handler, using the LogOptions defined

func (*CompositeMultiHandler) SetJson

func (h *CompositeMultiHandler) SetJson(writer io.Writer, options *LogOptions)

func (*CompositeMultiHandler) SetJsonFile

func (h *CompositeMultiHandler) SetJsonFile(filePath string, options *LogOptions)

Use built in rolling function

func (*CompositeMultiHandler) SetTerminal

func (h *CompositeMultiHandler) SetTerminal(writer io.Writer, options *LogOptions)

func (*CompositeMultiHandler) SetTerminalFile

func (h *CompositeMultiHandler) SetTerminalFile(filePath string, options *LogOptions)

Use built in rolling function

type ContextMap added in v0.20.0

type ContextMap map[string]interface{}

Internally used contextMap, allows conversion of map to map[string]string

func (ContextMap) Add added in v0.21.0

func (m ContextMap) Add(key string, value interface{})

func (ContextMap) StringMap added in v0.20.0

func (m ContextMap) StringMap() (newMap map[string]string)

Convert the context map to be string only values, any non string values are ignored

type Lazy added in v0.21.0

type Lazy struct {
	Fn interface{} // the function
}

The lazy structure to implement a function to be invoked only if needed

type LevelFilterHandler added in v0.21.0

type LevelFilterHandler struct {
	Level LogLevel
	// contains filtered or unexported fields
}

func (LevelFilterHandler) Log added in v0.21.0

func (h LevelFilterHandler) Log(r *Record) error

The implementation of the Log

type ListLogHandler

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

List log handler handles a list of LogHandlers

func NewListLogHandler

func NewListLogHandler(h1, h2 LogHandler) *ListLogHandler

Create a new list of log handlers

func (*ListLogHandler) Add

func (ll *ListLogHandler) Add(h LogHandler)

Add another log handler

func (*ListLogHandler) Del

func (ll *ListLogHandler) Del(h LogHandler)

Remove a log handler

func (*ListLogHandler) Log

func (ll *ListLogHandler) Log(r *Record) (err error)

Log the record

type LogFormat

type LogFormat interface {
	Format(r *Record) []byte
}

The log format interface

func FormatFunc added in v0.21.0

func FormatFunc(f func(*Record) []byte) LogFormat

FormatFunc returns a new Format object which uses the given function to perform record formatting.

func JsonFormatEx added in v0.21.0

func JsonFormatEx(pretty, lineSeparated bool) LogFormat

JsonFormatEx formats log records as JSON objects. If pretty is true, records will be pretty-printed. If lineSeparated is true, records will be logged with a new line between each record.

func TerminalFormatHandler

func TerminalFormatHandler(noColor bool, smallDate bool) LogFormat

Outputs to the terminal in a format like below INFO 09:11:32 server-engine.go:169: Request Stats

type LogHandler

type LogHandler interface {
	Log(*Record) error
}

The log handler interface

func CallerFileHandler

func CallerFileHandler(h LogHandler) LogHandler

func CallerFuncHandler

func CallerFuncHandler(h LogHandler) LogHandler

Adds in a context called `caller` to the record (contains file name and line number like `foo.go:12`) Uses the `log15.CallerFuncHandler` to perform this task

func FilterHandler

func FilterHandler(fn func(r *Record) bool, h LogHandler) LogHandler

Filter handler

func FuncHandler added in v0.21.0

func FuncHandler(fn func(r *Record) error) LogHandler

Function handler wraps the declared function and returns the handler for it

func HandlerFunc added in v0.20.0

func HandlerFunc(log func(message string, time time.Time, level LogLevel, call CallStack, context ContextMap) error) LogHandler

This function allows you to do a full declaration for the log, it is recommended you use FuncHandler instead

func LazyHandler added in v0.21.0

func LazyHandler(h LogHandler) LogHandler

LazyHandler writes all values to the wrapped handler after evaluating any lazy functions in the record's context. It is already wrapped around StreamHandler and SyslogHandler in this library, you'll only need it if you write your own Handler.

func LevelHandler

func LevelHandler(lvl LogLevel, h LogHandler) LogHandler

Filters out records which do not match the level Uses the `log15.FilterHandler` to perform this task

func MatchAbHandler

func MatchAbHandler(key string, value interface{}, a, b LogHandler) LogHandler

If match then A handler is called otherwise B handler is called

func MatchFilterHandler added in v0.21.0

func MatchFilterHandler(key string, value interface{}, h LogHandler) LogHandler

MatchFilterHandler returns a Handler that only writes records to the wrapped Handler if the given key in the logged context matches the value. For example, to only log records from your ui package:

log.MatchFilterHandler("pkg", "app/ui", log.StdoutHandler)

func MatchHandler

func MatchHandler(key string, value interface{}, h LogHandler) LogHandler

Filters out records which match the key value pair Uses the `log15.MatchFilterHandler` to perform this task

func MatchMapHandler

func MatchMapHandler(matchMap map[string]interface{}, a LogHandler) LogHandler

Match all values in map to log

func MinLevelHandler

func MinLevelHandler(lvl LogLevel, h LogHandler) LogHandler

Filters out records which do not match the level Uses the `log15.FilterHandler` to perform this task

func MultiHandler

func MultiHandler(hs ...LogHandler) LogHandler

func NilHandler

func NilHandler() LogHandler

The nil handler is used if logging for a specific request needs to be turned off

func NotLevelHandler

func NotLevelHandler(lvl LogLevel, h LogHandler) LogHandler

Filters out records which match the level Uses the `log15.FilterHandler` to perform this task

func NotMatchHandler

func NotMatchHandler(key string, value interface{}, h LogHandler) LogHandler

Filters out records which do not match the key value pair Uses the `log15.FilterHandler` to perform this task

func NotMatchMapHandler

func NotMatchMapHandler(matchMap map[string]interface{}, a LogHandler) LogHandler

Match !(Match all values in map to log) The inverse of MatchMapHandler

func StreamHandler

func StreamHandler(wr io.Writer, fmtr LogFormat) LogHandler

StreamHandler writes log records to an io.Writer with the given format. StreamHandler can be used to easily begin writing log records to other outputs.

StreamHandler wraps itself with LazyHandler and SyncHandler to evaluate Lazy objects and perform safe concurrent writes.

func SyncHandler added in v0.21.0

func SyncHandler(h LogHandler) LogHandler

SyncHandler can be wrapped around a handler to guarantee that only a single Log operation can proceed at a time. It's necessary for thread-safe concurrent writes.

type LogLevel

type LogLevel int

The log level type

const (
	LvlCrit  LogLevel = iota // Critical
	LvlError                 // Error
	LvlWarn                  // Warning
	LvlInfo                  // Information
	LvlDebug                 // Debug
)

type LogOptions

type LogOptions struct {
	Ctx                    *config.Context
	ReplaceExistingHandler bool
	HandlerWrap            ParentLogHandler
	Levels                 []LogLevel
	ExtendedOptions        map[string]interface{}
}

Used for the callback to LogFunctionMap

func NewLogOptions

func NewLogOptions(cfg *config.Context, replaceHandler bool, phandler ParentLogHandler, lvl ...LogLevel) (logOptions *LogOptions)

Create a new log options

func (*LogOptions) GetBoolDefault

func (l *LogOptions) GetBoolDefault(option string, value bool) bool

Gets a boolean option with default

func (*LogOptions) GetIntDefault

func (l *LogOptions) GetIntDefault(option string, value int) int

Gets an int option with default

func (*LogOptions) GetStringDefault

func (l *LogOptions) GetStringDefault(option, value string) string

Gets a string option with default

func (*LogOptions) SetExtendedOptions

func (l *LogOptions) SetExtendedOptions(options ...interface{})

Assumes options will be an even number and have a string, value syntax

type LogStackHandler

type LogStackHandler interface {
	LogHandler
	GetStack() int
}

The log stack handler interface

type MultiLogger

type MultiLogger interface {
	// New returns a new Logger that has this logger's context plus the given context
	New(ctx ...interface{}) MultiLogger

	// SetHandler updates the logger to write records to the specified handler.
	SetHandler(h LogHandler)

	// Set the stack depth for the logger
	SetStackDepth(int) MultiLogger

	// Log a message at the given level with context key/value pairs
	Debug(msg string, ctx ...interface{})

	// Log a message at the given level formatting message with the parameters
	Debugf(msg string, params ...interface{})

	// Log a message at the given level with context key/value pairs
	Info(msg string, ctx ...interface{})

	// Log a message at the given level formatting message with the parameters
	Infof(msg string, params ...interface{})

	// Log a message at the given level with context key/value pairs
	Warn(msg string, ctx ...interface{})

	// Log a message at the given level formatting message with the parameters
	Warnf(msg string, params ...interface{})

	// Log a message at the given level with context key/value pairs
	Error(msg string, ctx ...interface{})

	// Log a message at the given level formatting message with the parameters
	Errorf(msg string, params ...interface{})

	// Log a message at the given level with context key/value pairs
	Crit(msg string, ctx ...interface{})

	// Log a message at the given level formatting message with the parameters
	Critf(msg string, params ...interface{})

	// Log a message at the given level with context key/value pairs and exits
	Fatal(msg string, ctx ...interface{})

	// Log a message at the given level formatting message with the parameters and exits
	Fatalf(msg string, params ...interface{})

	// Log a message at the given level with context key/value pairs and panics
	Panic(msg string, ctx ...interface{})

	// Log a message at the given level formatting message with the parameters and panics
	Panicf(msg string, params ...interface{})
}

The Multilogger reduces the number of exposed defined logging variables, and allows the output to be easily refined

func New

func New(ctx ...interface{}) MultiLogger

Create a new logger

type ParentLogHandler

type ParentLogHandler interface {
	SetChild(handler LogHandler) LogHandler
}

The log handler interface which has child logs

func NewParentLogHandler

func NewParentLogHandler(callBack func(child LogHandler) LogHandler) ParentLogHandler

Create a new parent log handler

type Record added in v0.21.0

type Record struct {
	Message string     // The message
	Time    time.Time  // The time
	Level   LogLevel   //The level
	Call    CallStack  // The call stack if built
	Context ContextMap // The context
}

The log record

func NewRecord added in v0.21.0

func NewRecord(message string, level LogLevel) *Record

type RevelLogger

type RevelLogger struct {
	log15.Logger
}

This type implements the MultiLogger

func (*RevelLogger) Critf

func (rl *RevelLogger) Critf(msg string, param ...interface{})

Print a formatted critical message

func (*RevelLogger) Debugf

func (rl *RevelLogger) Debugf(msg string, param ...interface{})

func (*RevelLogger) Errorf

func (rl *RevelLogger) Errorf(msg string, param ...interface{})

Print a formatted error message

func (*RevelLogger) Fatal

func (rl *RevelLogger) Fatal(msg string, ctx ...interface{})

Print a critical message and call os.Exit(1)

func (*RevelLogger) Fatalf

func (rl *RevelLogger) Fatalf(msg string, param ...interface{})

Print a formatted fatal message

func (*RevelLogger) Infof

func (rl *RevelLogger) Infof(msg string, param ...interface{})

Print a formatted info message

func (*RevelLogger) New

func (rl *RevelLogger) New(ctx ...interface{}) MultiLogger

Override log15 method

func (*RevelLogger) Panic

func (rl *RevelLogger) Panic(msg string, ctx ...interface{})

Print a critical message and panic

func (*RevelLogger) Panicf

func (rl *RevelLogger) Panicf(msg string, param ...interface{})

Print a formatted panic message

func (*RevelLogger) SetHandler

func (rl *RevelLogger) SetHandler(h LogHandler)

Set the handler in the Logger

func (*RevelLogger) SetStackDepth

func (rl *RevelLogger) SetStackDepth(amount int) MultiLogger

Set the stack level to check for the caller

func (*RevelLogger) Warnf

func (rl *RevelLogger) Warnf(msg string, param ...interface{})

Print a formatted warn message

Jump to

Keyboard shortcuts

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