log

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2019 License: GPL-3.0, Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package log provides an opinionated, simple toolkit for best-practice logging.

Index

Constants

View Source
const (
	ZapLogger     = "zap"
	Log15Logger   = "log15"
	DefaultLogger = Log15Logger
)

Variables

View Source
var (
	StdoutHandler = StreamHandler(os.Stdout, LogfmtFormat())
	StderrHandler = StreamHandler(os.Stderr, LogfmtFormat())
)
View Source
var Must muster

The Must object provides the following Handler creation functions which instead of returning an error parameter only return a Handler and panic on failure: FileHandler, NetHandler, SyslogHandler, SyslogNetHandler

Functions

func ChangeGlobalLogLevel

func ChangeGlobalLogLevel(glogger *GlogHandler, lvl Lvl) error

func ChangeLogLevelWithID

func ChangeLogLevelWithID(mi ModuleID, lvl Lvl) error

ChangeLogLevelWithName changes the log level of loggers with given ModuleID.

func ChangeLogLevelWithName

func ChangeLogLevelWithName(moduleName string, lvl Lvl) error

ChangeLogLevelWithName changes the log level of loggers with given ModuleName.

func Fatalf

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

Fatalf formats a message to standard error and exits the program. The message is also printed to standard output if standard error is redirected to a different file.

func GetModuleName

func GetModuleName(mi ModuleID) string

func PrintOrigins

func PrintOrigins(print bool)

PrintOrigins sets or unsets log location (file:line) printing for terminal format output.

func SetBaseLogger

func SetBaseLogger()

Types

type Ctx

type Ctx map[string]interface{}

Ctx is a map of key/value pairs to pass as context to a log function Use this only if you really need greater safety around the arguments you pass to the logging functions.

type Format

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

func FormatFunc

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

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

func JsonFormat

func JsonFormat() Format

JsonFormat formats log records as JSON objects separated by newlines. It is the equivalent of JsonFormatEx(false, true).

func JsonFormatEx

func JsonFormatEx(pretty, lineSeparated bool) Format

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 LogfmtFormat

func LogfmtFormat() Format

LogfmtFormat prints records in logfmt format, an easy machine-parseable but human-readable format for key/value pairs.

For more details see: http://godoc.org/github.com/kr/logfmt

func TerminalFormat

func TerminalFormat(usecolor bool) Format

TerminalFormat formats log records optimized for human readability on a terminal with color-coded level output and terser human friendly timestamp. This format should only be used for interactive programs or while developing.

[TIME] [LEVEL] MESAGE key=value key=value ...

Example:

[May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002

type GlogHandler

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

GlogHandler is a log handler that mimics the filtering features of Google's glog logger: setting global log levels; overriding with callsite pattern matches; and requesting backtraces at certain positions.

func NewGlogHandler

func NewGlogHandler(h Handler) *GlogHandler

NewGlogHandler creates a new log handler with filtering functionality similar to Google's glog logger. The returned handler implements Handler.

func (*GlogHandler) BacktraceAt

func (h *GlogHandler) BacktraceAt(location string) error

BacktraceAt sets the glog backtrace location. When set to a file and line number holding a logging statement, a stack trace will be written to the Info log whenever execution hits that statement.

Unlike with Vmodule, the ".go" must be present.

func (*GlogHandler) Log

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

Log implements Handler.Log, filtering a log record through the global, local and backtrace filters, finally emitting it if either allow it through.

func (*GlogHandler) Verbosity

func (h *GlogHandler) Verbosity(level Lvl)

Verbosity sets the glog verbosity ceiling. The verbosity of individual packages and source files can be raised using Vmodule.

func (*GlogHandler) Vmodule

func (h *GlogHandler) Vmodule(ruleset string) error

Vmodule sets the glog verbosity pattern.

The syntax of the argument is a comma-separated list of pattern=N, where the pattern is a literal file name or "glob" pattern matching and N is a V level.

For instance:

pattern="gopher.go=3"
 sets the V level to 3 in all Go files named "gopher.go"

pattern="foo=3"
 sets V to 3 in all files of any packages whose import path ends in "foo"

pattern="foo/*=3"
 sets V to 3 in all files of any packages whose import path contains "foo"

type Handler

type Handler interface {
	Log(r *Record) error
}

A Logger prints its log records by writing to a Handler. The Handler interface defines where and how log records are written. Handlers are composable, providing you great flexibility in combining them to achieve the logging structure that suits your applications.

func BufferedHandler

func BufferedHandler(bufSize int, h Handler) Handler

BufferedHandler writes all records to a buffered channel of the given size which flushes into the wrapped handler whenever it is available for writing. Since these writes happen asynchronously, all writes to a BufferedHandler never return an error and any errors from the wrapped handler are ignored.

func CallerFileHandler

func CallerFileHandler(h Handler) Handler

CallerFileHandler returns a Handler that adds the line number and file of the calling function to the context with key "caller".

func CallerFuncHandler

func CallerFuncHandler(h Handler) Handler

CallerFuncHandler returns a Handler that adds the calling function name to the context with key "fn".

func CallerStackHandler

func CallerStackHandler(format string, h Handler) Handler

CallerStackHandler returns a Handler that adds a stack trace to the context with key "stack". The stack trace is formated as a space separated list of call sites inside matching []'s. The most recent call site is listed first. Each call site is formatted according to format. See the documentation of package github.com/go-stack/stack for the list of supported formats.

func ChannelHandler

func ChannelHandler(recs chan<- *Record) Handler

ChannelHandler writes all records to the given channel. It blocks if the channel is full. Useful for async processing of log messages, it's used by BufferedHandler.

func DiscardHandler

func DiscardHandler() Handler

DiscardHandler reports success for all writes but does nothing. It is useful for dynamically disabling logging at runtime via a Logger's SetHandler method.

func FailoverHandler

func FailoverHandler(hs ...Handler) Handler

A FailoverHandler writes all log records to the first handler specified, but will failover and write to the second handler if the first handler has failed, and so on for all handlers specified. For example you might want to log to a network socket, but failover to writing to a file if the network fails, and then to standard out if the file write fails:

log.FailoverHandler(
    log.Must.NetHandler("tcp", ":9090", log.JsonFormat()),
    log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()),
    log.StdoutHandler)

All writes that do not go to the first handler will add context with keys of the form "failover_err_{idx}" which explain the error encountered while trying to write to the handlers before them in the list.

func FileHandler

func FileHandler(path string, fmtr Format) (Handler, error)

FileHandler returns a handler which writes log records to the give file using the given format. If the path already exists, FileHandler will append to the given file. If it does not, FileHandler will create the file with mode 0644.

func FilterHandler

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

FilterHandler returns a Handler that only writes records to the wrapped Handler if the given function evaluates true. For example, to only log records where the 'err' key is not nil:

logger.SetHandler(FilterHandler(func(r *Record) bool {
    for i := 0; i < len(r.Ctx); i += 2 {
        if r.Ctx[i] == "err" {
            return r.Ctx[i+1] != nil
        }
    }
    return false
}, h))

func FuncHandler

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

FuncHandler returns a Handler that logs records with the given function.

func LazyHandler

func LazyHandler(h Handler) Handler

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 LvlFilterHandler

func LvlFilterHandler(maxLvl Lvl, h Handler) Handler

LvlFilterHandler returns a Handler that only writes records which are less than the given verbosity level to the wrapped Handler. For example, to only log Error/Crit records:

log.LvlFilterHandler(log.LvlError, log.StdoutHandler)

func MatchFilterHandler

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

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 MultiHandler

func MultiHandler(hs ...Handler) Handler

A MultiHandler dispatches any write to each of its handlers. This is useful for writing different types of log information to different locations. For example, to log to a file and standard error:

log.MultiHandler(
    log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()),
    log.StderrHandler)

func NetHandler

func NetHandler(network, addr string, fmtr Format) (Handler, error)

NetHandler opens a socket to the given address and writes records over the connection.

func StreamHandler

func StreamHandler(wr io.Writer, fmtr Format) Handler

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

func SyncHandler(h Handler) Handler

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.

func SyslogHandler

func SyslogHandler(priority syslog.Priority, tag string, fmtr Format) (Handler, error)

SyslogHandler opens a connection to the system syslog daemon by calling syslog.New and writes all records to it.

func SyslogNetHandler

func SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) (Handler, error)

SyslogNetHandler opens a connection to a log daemon over the network and writes all log records to it.

type Lazy

type Lazy struct {
	Fn interface{}
}

Lazy allows you to defer calculation of a logged value that is expensive to compute until it is certain that it must be evaluated with the given filters.

Lazy may also be used in conjunction with a Logger's New() function to generate a child logger which always reports the current value of changing state.

You may wrap any function which takes no arguments to Lazy. It may return any number of values of any type.

type Logger

type Logger interface {
	NewWith(keysAndValues ...interface{}) Logger

	Trace(msg string, keysAndValues ...interface{})
	Debug(msg string, keysAndValues ...interface{})
	Info(msg string, keysAndValues ...interface{})
	Warn(msg string, keysAndValues ...interface{})
	Error(msg string, keysAndValues ...interface{})
	ErrorWithStack(msg string, keysAndValues ...interface{})
	Crit(msg string, keysAndValues ...interface{})
	CritWithStack(msg string, keysAndValues ...interface{})

	// GetHandler gets the handler associated with the logger.
	GetHandler() Handler
	// SetHandler updates the logger to write records to the specified handler.
	SetHandler(h Handler)
	// contains filtered or unexported methods
}

func NewModuleLogger

func NewModuleLogger(mi ModuleID) Logger

func Root

func Root() Logger

Root returns the root logger

type Lvl

type Lvl int
const (
	LvlCrit Lvl = iota
	LvlError
	LvlWarn
	LvlInfo
	LvlDebug
	LvlTrace
	LvlEnd
)

func (Lvl) AlignedString

func (l Lvl) AlignedString() string

Aligned returns a 5-character string containing the name of a Lvl.

func (Lvl) String

func (l Lvl) String() string

Strings returns the name of a Lvl.

type ModuleID

type ModuleID int
const (
	// 0
	BaseLogger ModuleID = iota

	// 1~10
	AccountsAbiBind
	AccountsKeystore
	API
	APIDebug
	Blockchain
	BlockchainState
	BlockchainTypes
	BlockchainTypesAccount
	BlockchainTypesAccountKey
	CMDIstanbul

	// 11~20
	CMDKBN
	CMDKCN
	CMDKEN
	CMDKGEN
	CMDKlay
	CMDKPN
	CMDKSCN
	CMDUtils
	CMDUtilsNodeCMD
	Common

	// 21~30
	ConsensusClique
	ConsensusGxhash
	ConsensusIstanbul
	ConsensusIstanbulBackend
	ConsensusIstanbulCore
	ConsensusIstanbulValidator
	Console
	DatasyncDownloader
	DatasyncFetcher
	Governance

	// 31~40
	Metrics
	NetworksGRPC
	NetworksP2P
	NetworksP2PDiscover
	NetworksP2PNat
	NetworksP2PSimulations
	NetworksP2PSimulationsAdapters
	NetworksP2PSimulationsCnism
	NetworksRPC
	Node

	// 41~50
	NodeCN
	NodeCNFilters
	NodeCNTracers
	Reward
	ServiceChain
	StorageDatabase
	StorageStateDB
	VM
	Work
	CMDKSPN

	// 51~60
	CMDKSEN

	// ModuleNameLen should be placed at the end of the list.
	ModuleNameLen
)

NOTE-Klaytn-Log Please add module in lexicographical order.

func GetModuleID

func GetModuleID(moduleName string) ModuleID

func (ModuleID) String

func (mi ModuleID) String() string

type Record

type Record struct {
	Time     time.Time
	Lvl      Lvl
	Msg      string
	Ctx      []interface{}
	Call     stack.Call
	KeyNames RecordKeyNames
}

type RecordKeyNames

type RecordKeyNames struct {
	Time string
	Msg  string
	Lvl  string
}

type TerminalStringer

type TerminalStringer interface {
	TerminalString() string
}

TerminalStringer is an analogous interface to the stdlib stringer, allowing own types to have custom shortened serialization formats when printed to the screen.

Directories

Path Synopsis
Package term contains checking specific operating system terminals.
Package term contains checking specific operating system terminals.

Jump to

Keyboard shortcuts

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