Documentation ¶
Index ¶
- Constants
- Variables
- func Debug(args ...interface{})
- func Debugf(msg string, args ...interface{})
- func DisableExistingLoggers()
- func Error(args ...interface{})
- func Errorf(msg string, args ...interface{})
- func Fatal(args ...interface{})
- func Fatalf(msg string, args ...interface{})
- func Flush() error
- func FormatTime(record *LogRecord, datefmt string) string
- func Info(args ...interface{})
- func Infof(msg string, args ...interface{})
- func IsColorTerminal() (bool, bool)
- func LoadJSONConfig(config []byte) error
- func Notice(args ...interface{})
- func Noticef(msg string, args ...interface{})
- func Panic(msg string, args ...interface{})
- func Panicf(msg string, args ...interface{})
- func RegisterConstructor(name string, c Constructor)
- func RegisterFormatter(name string, formatter Formatter)
- func RegisterHandler(name string, handler Handler)
- func RegisterLevel(name string, level Level)
- func Warn(args ...interface{})
- func Warnf(msg string, args ...interface{})
- func Warning(args ...interface{})
- func Warningf(msg string, args ...interface{})
- type Config
- type ConfigLoader
- type Constructor
- type Fields
- type FileHandler
- func (hdlr *FileHandler) ApplyOptions(options ...Option) *FileHandler
- func (hdlr *FileHandler) Close() error
- func (hdlr *FileHandler) Emit(record *LogRecord)
- func (hdlr *FileHandler) Filter(record *LogRecord) bool
- func (hdlr *FileHandler) Flush() error
- func (hdlr *FileHandler) LoadConfig(c map[string]interface{}) error
- func (hdlr *FileHandler) SetPath(path string) *FileHandler
- type Formatter
- type Handler
- type JSONFormatter
- type Level
- type LogConfig
- type LogRecord
- type Logger
- func (lg *Logger) AddHandlers(handlers ...Handler) *Logger
- func (lg *Logger) ApplyOptions(options ...Option) *Logger
- func (lg *Logger) Close() error
- func (lg Logger) Debug(args ...interface{})
- func (lg Logger) Debugf(msg string, args ...interface{})
- func (lg Logger) Error(args ...interface{})
- func (lg Logger) Errorf(msg string, args ...interface{})
- func (lg Logger) Fatal(args ...interface{})
- func (lg Logger) Fatalf(msg string, args ...interface{})
- func (lg Logger) Filter(record *LogRecord) bool
- func (lg *Logger) Flush() error
- func (lg *Logger) Handle(record *LogRecord)
- func (lg Logger) Info(args ...interface{})
- func (lg Logger) Infof(msg string, args ...interface{})
- func (lg *Logger) LoadConfig(c map[string]interface{}) error
- func (lg Logger) Log(level Level, args ...interface{})
- func (lg Logger) Logf(level Level, msg string, args ...interface{})
- func (lg Logger) Notice(args ...interface{})
- func (lg Logger) Noticef(msg string, args ...interface{})
- func (lg Logger) Panic(msg string, args ...interface{})
- func (lg Logger) Panicf(msg string, args ...interface{})
- func (lg Logger) Warn(args ...interface{})
- func (lg Logger) Warnf(msg string, args ...interface{})
- type NullHandler
- type Option
- type StreamHandler
- func (hdlr *StreamHandler) ApplyOptions(options ...Option) *StreamHandler
- func (hdlr *StreamHandler) Close() error
- func (hdlr *StreamHandler) Emit(record *LogRecord)
- func (hdlr *StreamHandler) Filter(record *LogRecord) bool
- func (hdlr *StreamHandler) Flush() error
- func (hdlr *StreamHandler) LoadConfig(c map[string]interface{}) error
- type TextFormatter
Constants ¶
const ( // DefaultFmtTemplate is the default log string format value for TextFormatter DefaultFmtTemplate = "%(time) %(color)%(levelname)%(endColor) %(filename):%(lineno) | %(message)" // DefaultDateFmtTemplate is the default log time string format value for TextFormatter DefaultDateFmtTemplate = "%Y-%m-%d %H:%M:%S" )
const ( // DefaultCallerStackDepth is 2 because you should ascend 2 frames // to get true caller function by default DefaultCallerStackDepth = 2 )
const (
// RootLoggerName is the name of root logger
RootLoggerName = "root"
)
Variables ¶
var ( // LogRecordFieldRegexp is the field regexp // for example, I will replace %(name) of real record name // TODO support %[(name)][flags][width].[precision]typecode LogRecordFieldRegexp = regexp.MustCompile(`\%\(\w+\)`) // DefaultFormatter is the default formatter of TextFormatter without color DefaultFormatter = &TextFormatter{ Fmt: DefaultFmtTemplate, DateFmt: DefaultDateFmtTemplate, } // TerminalFormatter is an TextFormatter with color TerminalFormatter = &TextFormatter{ Fmt: DefaultFmtTemplate, DateFmt: DefaultDateFmtTemplate, EnableColors: true, } // ColorHash describes colors of different log level // you can add new color for your own log level ColorHash = map[Level]int{ DebugLevel: blue, InfoLevel: green, WarnLevel: yellow, ErrorLevel: red, NoticeLevel: darkGreen, FatalLevel: red, } )
var ( // Discard is an io.ReadWriteCloser on which all Read | Write | Close calls succeed // without doing anything. Discard = devNull(0) )
var ( // ForceColor forces formatter use color output ForceColor = false )
Functions ¶
func DisableExistingLoggers ¶
func DisableExistingLoggers()
DisableExistingLoggers closes all existing loggers and unregister them
func FormatTime ¶
FormatTime returns the creation time of the specified LogRecord as formatted text.
func IsColorTerminal ¶
IsColorTerminal return isTerminal and isColorTerminal
func LoadJSONConfig ¶
LoadJSONConfig loads a json config if DisableExistingLoggers is true, all existing loggers will be closed, then a new root logger will be created
func RegisterConstructor ¶
func RegisterConstructor(name string, c Constructor)
RegisterConstructor binds name and Constructor
func RegisterFormatter ¶
RegisterFormatter binds name and Formatter
func RegisterHandler ¶
RegisterHandler binds name and Handler
func RegisterLevel ¶
RegisterLevel binds name and level
Types ¶
type ConfigLoader ¶
ConfigLoader is an interface which con load map[string]interface{} config
type Constructor ¶
type Constructor func() ConfigLoader
Constructor is a function which returns an ConfigLoader
func GetConstructor ¶
func GetConstructor(name string) Constructor
GetConstructor returns an Constructor registered with the given name if not, returns nil
type Fields ¶
type Fields map[string]interface{}
Fields is an alias to man[string]interface{}
func (Fields) ToKVString ¶
ToKVString convert Fields to string likes k1=v1 k2=v2
type FileHandler ¶
type FileHandler struct { Name string Level Level Formatter Formatter Output flushWriteCloser Path string // contains filtered or unexported fields }
FileHandler is a handler similar to SteamHandler if specified file and it will close the file
func NewFileHandler ¶
func NewFileHandler(options ...Option) *FileHandler
NewFileHandler returns a new FileHandler fully initialized
func (*FileHandler) ApplyOptions ¶
func (hdlr *FileHandler) ApplyOptions(options ...Option) *FileHandler
ApplyOptions applys all option to StreamHandler
func (*FileHandler) Filter ¶
func (hdlr *FileHandler) Filter(record *LogRecord) bool
Filter checks if handler should filter the specified record
func (*FileHandler) Flush ¶
func (hdlr *FileHandler) Flush() error
Flush flushes the file system's in-memory copy of recently written data to disk.
func (*FileHandler) LoadConfig ¶
func (hdlr *FileHandler) LoadConfig(c map[string]interface{}) error
LoadConfig loads config from its input and stores it in the value pointed to by c
func (*FileHandler) SetPath ¶
func (hdlr *FileHandler) SetPath(path string) *FileHandler
SetPath opens file located in the path, if not, create it
type Formatter ¶
Formatter is an interface which can convert a LogRecord to string
func GetFormatter ¶
GetFormatter returns an Formatter registered with the given name
type Handler ¶
type Handler interface { // Filter checks if handler should filter the specified record Filter(*LogRecord) bool // Emit log record to output - e.g. stderr or file Emit(*LogRecord) // Flush flushes the file system's in-memory copy of recently written data to disk. // Typically, calls the file.Sync() Flush() error // Close output stream, if not return error Close() error }
Handler specifies how to write a LoadConfig, appropriately formatted, to output.
func GetHandler ¶
GetHandler returns a Handler registered with the given name
type JSONFormatter ¶
type JSONFormatter struct { Datefmt string ConfigLoader }
JSONFormatter can convert LogRecord to json text
func NewJSONFormatter ¶
func NewJSONFormatter() *JSONFormatter
NewJSONFormatter returns a JSONFormatter with default config
func (*JSONFormatter) Format ¶
func (jf *JSONFormatter) Format(record *LogRecord) (string, error)
Format converts the specified record to json string.
func (*JSONFormatter) LoadConfig ¶
func (jf *JSONFormatter) LoadConfig(c map[string]interface{}) error
LoadConfig loads config from its input and stores it in the value pointed to by c
type Level ¶
type Level int
Level is a logging priority. Note that Level satisfies the Option interface
const ( // NothingLevel log level only used in filter NothingLevel Level = 0 // DebugLevel log level DebugLevel Level = 1 //0x00000001 // InfoLevel log level InfoLevel Level = 2 //0x00000010 // WarnLevel log level WarnLevel Level = 4 //0x00000100 // WarningLevel is alias of WARN WarningLevel Level = 4 //0x00000100 // ErrorLevel log level ErrorLevel Level = 8 //0x00001000 // NoticeLevel log level NoticeLevel Level = 16 //0x00010000 // FatalLevel log level FatalLevel Level = 32 //0x00100000 // AllLevel log level only used in filter AllLevel Level = 255 //0x11111111 )
type LogConfig ¶
type LogConfig struct { DisableExistingLoggers bool `json:"disableExistingLoggers"` Formatters map[string]map[string]interface{} `json:"formatters"` Handlers map[string]map[string]interface{} `json:"handlers"` Loggers map[string]map[string]interface{} `json:"loggers"` }
LogConfig defines the configuration of logger
type LogRecord ¶
type LogRecord struct { Name string Level Level LevelName string PathName string FileName string FuncName string ShortFuncName string Line int Time time.Time // msg could be "" Msg string Args []interface{} // extract fields from args Fields Fields }
LogRecord defines a real log record should be
func NewLogRecord ¶
func NewLogRecord(name string, level Level, pathname string, funcname string, line int, msg string, args ...interface{}) *LogRecord
NewLogRecord returns a new log record
func (*LogRecord) ExtractFieldsFromArgs ¶
func (lr *LogRecord) ExtractFieldsFromArgs()
ExtractFieldsFromArgs extracts fields (Fields) from args Fields must be the last element in args
func (LogRecord) GetMessage ¶
GetMessage formats record message by msg and args
type Logger ¶
type Logger struct { Name string Handlers []Handler Level Level // callerStackDepth is the number of stack frames to ascend // you should change it if you implement your own log function CallerStackDepth int EnableRuntimeCaller bool }
Logger entries pass through the formatter before logged to Output. The included formatters are `TextFormatter` and `JSONFormatter` for which TextFormatter is the default. In development (when a TTY is attached) it logs with colors, but to a file it wouldn't. You can easily implement your own that implements the `Formatter` interface, see the `README` or included formatters for examples.
func AddHandlers ¶
AddHandlers is an alias of root.AddHandler
func ApplyOptions ¶
ApplyOptions is an alias of root.ApplyOptions
func GetLogger ¶
GetLogger returns an logger by name if not, create one and add it to logger register
func (*Logger) AddHandlers ¶
AddHandlers adds handler to logger
func (*Logger) ApplyOptions ¶
ApplyOptions applys all option to Logger
func (Logger) Debug ¶
func (lg Logger) Debug(args ...interface{})
Debug emits log message with DEBUG level
func (Logger) Error ¶
func (lg Logger) Error(args ...interface{})
Error emits log message with ERROR level
func (Logger) Fatal ¶
func (lg Logger) Fatal(args ...interface{})
Fatal emits log message with FATAL level
func (Logger) Info ¶
func (lg Logger) Info(args ...interface{})
Info emits log message with INFO level
func (*Logger) LoadConfig ¶
LoadConfig loads config from its input and stores it in the value pointed to by c
func (Logger) Notice ¶
func (lg Logger) Notice(args ...interface{})
Notice emits log message with NOTICE level
type NullHandler ¶
type NullHandler struct {
Name string
}
NullHandler is an example handler doing nothing
func (*NullHandler) Close ¶
func (hdlr *NullHandler) Close() error
Close output stream, if not return error
func (*NullHandler) Emit ¶
func (hdlr *NullHandler) Emit(*LogRecord)
Emit log record to output - e.g. stderr or file
func (*NullHandler) Filter ¶
func (hdlr *NullHandler) Filter(*LogRecord) bool
Filter checks if handler should filter the specified record
func (*NullHandler) Flush ¶
func (hdlr *NullHandler) Flush() error
Flush flushes in-memory data to disk
func (*NullHandler) LoadConfig ¶
func (hdlr *NullHandler) LoadConfig(config map[string]interface{}) error
LoadConfig loads config from its input and stores it in the value pointed to by c
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option is an interface which is used to set options for the target
func OptionCallerStackDepth ¶
OptionCallerStackDepth is an option. used in every target which has fields named `CallerStackDepth`
func OptionDiscardOutput ¶
func OptionDiscardOutput() Option
OptionDiscardOutput is an option used in every target which has fields named `Output` and make all Read | Write | Close calls succeed without doing anything.
func OptionEnableRuntimeCaller ¶
OptionEnableRuntimeCaller is an option useed in : used in every target which has fields named `EnableRuntimeCaller`
func OptionHandlers ¶
OptionHandlers is an option used in every target which has fields named `Handlers`
func OptionName ¶
OptionName is an option used in every target which has fields named `Name`
func OptionOutput ¶
func OptionOutput(out io.WriteCloser) Option
OptionOutput is an option used in every target which has fields named `Output`
type StreamHandler ¶
type StreamHandler struct { Name string Level Level Formatter Formatter Output flushWriter // contains filtered or unexported fields }
StreamHandler is a handler which writes logging records, appropriately formatted, to a stream. Note that this handler does not close the stream, as os.Stdout or os.Stderr may be used.
func NewStreamHandler ¶
func NewStreamHandler(options ...Option) *StreamHandler
NewStreamHandler returns a new StreamHandler fully initialized
func (*StreamHandler) ApplyOptions ¶
func (hdlr *StreamHandler) ApplyOptions(options ...Option) *StreamHandler
ApplyOptions applys all option to StreamHandler
func (*StreamHandler) Close ¶
func (hdlr *StreamHandler) Close() error
Close output stream, if not return error
func (*StreamHandler) Emit ¶
func (hdlr *StreamHandler) Emit(record *LogRecord)
Emit log record to output - e.g. stderr or file
func (*StreamHandler) Filter ¶
func (hdlr *StreamHandler) Filter(record *LogRecord) bool
Filter checks if handler should filter the specified record
func (*StreamHandler) Flush ¶
func (hdlr *StreamHandler) Flush() error
Flush flushes the file system's in-memory copy to disk
func (*StreamHandler) LoadConfig ¶
func (hdlr *StreamHandler) LoadConfig(c map[string]interface{}) error
LoadConfig loads config from its input and stores it in the value pointed to by c
type TextFormatter ¶
type TextFormatter struct { Fmt string DateFmt string EnableColors bool ConfigLoader // contains filtered or unexported fields }
TextFormatter is the default formatter used to convert a LogRecord to text.
The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user's message and arguments are pre- formatted into a LogRecord's message attribute. Currently, the useful attributes in a LogRecord are described by:
%(name) Name of the logger (logging channel) %(levelno) Numeric logging level for the message (DEBUG, INFO,
WARNING, ERROR, CRITICAL)
%(levelname) Text logging level for the message ("DEBUG", "INFO",
"WARNING", "ERROR", "CRITICAL")
%(pathname) Full pathname of the source file where the logging
call was issued (if available) or maybe ??
%(filename) Filename portion of pathname %(lineno) Source line number where the logging call was issued
(if available)
%(funcname) Function name of caller or maybe ?? %(time) Textual time when the LogRecord was created %(message) The result of record.getMessage(), computed just as
the record is emitted
%(color) Print color %(endColor) Reset color
func NewTextFormatter ¶
func NewTextFormatter() *TextFormatter
NewTextFormatter return a new TextFormatter with default config
func (*TextFormatter) Format ¶
func (tf *TextFormatter) Format(record *LogRecord) (string, error)
Format converts the specified record to string. bench mark with 10 fields go template 33153 ns/op ReplaceAllStringFunc 8420 ns/op field sequence 5046 ns/op
func (*TextFormatter) LoadConfig ¶
func (tf *TextFormatter) LoadConfig(c map[string]interface{}) error
LoadConfig loads config from its input and stores it in the value pointed to by c