Documentation
¶
Overview ¶
Package log is a simple, highly configurable, structured logging that is a near drop in replacement for the std library log.
Usage
package main import ( "github.com/go-playground/log" "github.com/go-playground/log/handlers/console" ) func main() { cLog := console.New() log.RegisterHandler(cLog, log.AllLevels...) // Trace defer log.Trace("trace").End() log.Debug("debug") log.Info("info") log.Notice("notice") log.Warn("warn") log.Error("error") // log.Panic("panic") // this will panic log.Alert("alert") // log.Fatal("fatal") // this will call os.Exit(1) // logging with fields can be used with any of the above log.WithFields(log.F("key", "value")).Info("test info") }
Adding your own Handler
package main import ( "bytes" "fmt" "github.com/go-playground/log" ) // CustomHandler is your custom handler type CustomHandler struct { // whatever properties you need buffer uint // channel buffer } // Run starts the logger consuming on the returned channed func (c *CustomHandler) Run() chan<- *log.Entry { // in a big high traffic app, set a higher buffer ch := make(chan *log.Entry, c.buffer) // can run as many consumers on the channel as you want, // depending on the buffer size or your needs go func(entries <-chan *log.Entry) { // below prints to os.Stderr but could marshal to JSON // and send to central logging server var e *log.Entry b := new(bytes.Buffer) for e = range entries { b.Reset() b.WriteString(e.Message) for _, f := range e.Fields { fmt.Fprintf(b, " %s=%v", f.Key, f.Value) } fmt.Println(b.String()) e.WG.Done() // done writing the entry } }(ch) return ch } func main() { cLog := &CustomHandler{ buffer: 0, } log.RegisterHandler(cLog, log.AllLevels...) // Trace defer log.Trace("trace").End() log.Debug("debug") log.Info("info") log.Notice("notice") log.Warn("warn") log.Error("error") // log.Panic("panic") // this will panic log.Alert("alert") // log.Fatal("fatal") // this will call os.Exit(1) // logging with fields can be used with any of the above log.WithFields(log.F("key", "value")).Info("test info") }
Log Level Definitions
DebugLevel - Info useful to developers for debugging the application, not useful during operations. TraceLevel - Info useful to developers for debugging the application and reporting on possible bottlenecks. InfoLevel - Normal operational messages - may be harvested for reporting, measuring throughput, etc. - no action required. NoticeLevel - Normal but significant condition. Events that are unusual but not error conditions - might be summarized in an email to developers or admins to spot potential problems - no immediate action required. WarnLevel - Warning messages, not an error, but indication that an error will occur if action is not taken, e.g. file system 85% full - each item must be resolved within a given time. ErrorLevel - Non-urgent failures, these should be relayed to developers or admins; each item must be resolved within a given time. PanicLevel - A "panic" condition usually affecting multiple apps/servers/sites. At this level it would usually notify all tech staff on call. AlertLevel - Action must be taken immediately. Should be corrected immediately, therefore notify staff who can fix the problem. An example would be the loss of a primary ISP connection. FatalLevel - Should be corrected immediately, but indicates failure in a primary system, an example is a loss of a backup ISP connection. ( same as SYSLOG CRITICAL )
Index ¶
- Constants
- Variables
- func Alert(v ...interface{})
- func Alertf(msg string, v ...interface{})
- func Debug(v ...interface{})
- func Debugf(msg string, v ...interface{})
- func Error(v ...interface{})
- func Errorf(msg string, v ...interface{})
- func Fatal(v ...interface{})
- func Fatalf(msg string, v ...interface{})
- func Fatalln(v ...interface{})
- func HandleEntry(e *Entry)
- func HasHandlers() bool
- func Info(v ...interface{})
- func Infof(msg string, v ...interface{})
- func Notice(v ...interface{})
- func Noticef(msg string, v ...interface{})
- func Panic(v ...interface{})
- func Panicf(msg string, v ...interface{})
- func Panicln(v ...interface{})
- func Print(v ...interface{})
- func Printf(msg string, v ...interface{})
- func Println(v ...interface{})
- func RegisterDurationFunc(fn DurationFormatFunc)
- func RegisterHandler(handler Handler, levels ...Level)
- func SetApplicationID(id string)
- func SetCallerInfoLevels(levels ...Level)
- func SetCallerSkipDiff(diff uint8)
- func SetTimeFormat(format string)
- func Warn(v ...interface{})
- func Warnf(msg string, v ...interface{})
- type ANSIEscSeq
- type DurationFormatFunc
- type Entry
- func (e *Entry) Alert(v ...interface{})
- func (e *Entry) Alertf(msg string, v ...interface{})
- func (e *Entry) Consumed()
- func (e *Entry) Debug(v ...interface{})
- func (e *Entry) Debugf(msg string, v ...interface{})
- func (e *Entry) Error(v ...interface{})
- func (e *Entry) Errorf(msg string, v ...interface{})
- func (e *Entry) Fatal(v ...interface{})
- func (e *Entry) Fatalf(msg string, v ...interface{})
- func (e *Entry) Info(v ...interface{})
- func (e *Entry) Infof(msg string, v ...interface{})
- func (e *Entry) Notice(v ...interface{})
- func (e *Entry) Noticef(msg string, v ...interface{})
- func (e *Entry) Panic(v ...interface{})
- func (e *Entry) Panicf(msg string, v ...interface{})
- func (e *Entry) StackTrace() LeveledLogger
- func (e *Entry) Trace(v ...interface{}) Traceable
- func (e *Entry) Tracef(msg string, v ...interface{}) Traceable
- func (e *Entry) Warn(v ...interface{})
- func (e *Entry) Warnf(msg string, v ...interface{})
- func (e *Entry) WithFields(fields ...Field) LeveledLogger
- type Field
- type FilenameDisplay
- type Handler
- type HandlerChannels
- type Level
- type LevelHandlerChannels
- type LeveledLogger
- type TraceEntry
- type Traceable
Constants ¶
const ( Black ANSIEscSeq = "\x1b[30m" DarkGray = "\x1b[30;1m" Blue = "\x1b[34m" LightBlue = "\x1b[34;1m" Green = "\x1b[32m" LightGreen = "\x1b[32;1m" Cyan = "\x1b[36m" LightCyan = "\x1b[36;1m" Red = "\x1b[31m" LightRed = "\x1b[31;1m" Magenta = "\x1b[35m" LightMagenta = "\x1b[35;1m" Brown = "\x1b[33m" Yellow = "\x1b[33;1m" LightGray = "\x1b[37m" White = "\x1b[37;1m" Underscore = "\x1b[4m" Blink = "\x1b[5m" Inverse = "\x1b[7m" Reset = "\x1b[0m" )
ANSI escape sequences NOTE: in an standard xterm terminal the light colors will appear BOLD instead of the light variant
const ( // DefaultTimeFormat is the default time format when parsing Time values. // it is exposed to allow handlers to use and not have to redefine DefaultTimeFormat = "2006-01-02T15:04:05.000000000Z07:00" )
Variables ¶
var AllLevels = []Level{ DebugLevel, TraceLevel, InfoLevel, NoticeLevel, WarnLevel, ErrorLevel, PanicLevel, AlertLevel, FatalLevel, }
AllLevels is an array of all log levels, for easier registering of all levels to a handler
var (
Logger *logger
)
Logger is the default instance of the log package
Functions ¶
func Fatalf ¶
func Fatalf(msg string, v ...interface{})
Fatalf level formatted message, followed by an exit.
func HandleEntry ¶
func HandleEntry(e *Entry)
HandleEntry send the logs entry out to all the registered handlers
func HasHandlers ¶
func HasHandlers() bool
HasHandlers returns if any handlers have been registered.
func Panic ¶
func Panic(v ...interface{})
Panic logs an Panic level formatted message and then panics it is here to let this log package be a drop in replacement for the standard logger
func Panicf ¶
func Panicf(msg string, v ...interface{})
Panicf logs an Panic level formatted message and then panics it is here to let this log package be a near drop in replacement for the standard logger
func Panicln ¶
func Panicln(v ...interface{})
Panicln logs an Panic level formatted message and then panics it is here to let this log package be a near drop in replacement for the standard logger
func RegisterDurationFunc ¶
func RegisterDurationFunc(fn DurationFormatFunc)
RegisterDurationFunc registers a custom duration function for Trace events
func RegisterHandler ¶
RegisterHandler adds a new Log Handler and specifies what log levels the handler will be passed log entries for
func SetApplicationID ¶
func SetApplicationID(id string)
SetApplicationID tells the logger to set a constant application key that will be set on all log Entry objects. log does not care what it is, the application name, app name + hostname.... that's up to you it is needed by many logging platforms for separating logs by application and even by application server in a distributed app.
func SetCallerInfoLevels ¶
func SetCallerInfoLevels(levels ...Level)
SetCallerInfoLevels tells the logger to gather and set file and line number information on Entry objects for the provided log levels. By defaut all but TraceLevel, InfoLevel and NoticeLevel are set to gather information.
func SetCallerSkipDiff ¶
func SetCallerSkipDiff(diff uint8)
SetCallerSkipDiff adds the provided diff to the caller SkipLevel values. This is used when wrapping this library, you can set ths to increase the skip values passed to Caller that retrieves the file + line number info.
func SetTimeFormat ¶
func SetTimeFormat(format string)
SetTimeFormat sets the time format used for Trace events
Types ¶
type DurationFormatFunc ¶
DurationFormatFunc is the function called for parsing Trace Duration
type Entry ¶
type Entry struct { ApplicationID string `json:"appId"` Level Level `json:"level"` Timestamp time.Time `json:"timestamp"` Message string `json:"message"` Fields []Field `json:"fields"` File string `json:"file"` Line int `json:"line"` // contains filtered or unexported fields }
Entry represents a single log entry.
func (*Entry) Consumed ¶
func (e *Entry) Consumed()
Consumed lets the Entry and subsequently the Logger instance know that it has been used by a handler
func (*Entry) Fatal ¶
func (e *Entry) Fatal(v ...interface{})
Fatal level message, followed by an exit.
func (*Entry) Panic ¶
func (e *Entry) Panic(v ...interface{})
Panic logs an Error level formatted message and then panics
func (*Entry) StackTrace ¶
func (e *Entry) StackTrace() LeveledLogger
StackTrace adds a field with stack trace to the current log Entry.
func (*Entry) WithFields ¶
func (e *Entry) WithFields(fields ...Field) LeveledLogger
WithFields adds the provided fieldsto the current entry
type Field ¶
type Field struct { Key string `json:"key"` Value interface{} `json:"value"` }
Field contains a single key + value for structured logging.
type FilenameDisplay ¶
type FilenameDisplay uint8
FilenameDisplay is the type of file display output
const ( Lshortfile FilenameDisplay = iota Llongfile )
FilenameDisplay options
type HandlerChannels ¶
type HandlerChannels []chan<- *Entry
HandlerChannels is an array of handler channels
type Level ¶
type Level uint8
Level of the log
type LevelHandlerChannels ¶
type LevelHandlerChannels map[Level]HandlerChannels
LevelHandlerChannels is a group of Handler channels mapped by Level
type LeveledLogger ¶
type LeveledLogger interface { Debug(v ...interface{}) Trace(v ...interface{}) Traceable Info(v ...interface{}) Notice(v ...interface{}) Warn(v ...interface{}) Error(v ...interface{}) Panic(v ...interface{}) Alert(v ...interface{}) Fatal(v ...interface{}) Debugf(msg string, v ...interface{}) Tracef(msg string, v ...interface{}) Traceable Infof(msg string, v ...interface{}) Noticef(msg string, v ...interface{}) Warnf(msg string, v ...interface{}) Errorf(msg string, v ...interface{}) Panicf(msg string, v ...interface{}) Alertf(msg string, v ...interface{}) Fatalf(msg string, v ...interface{}) WithFields(...Field) LeveledLogger StackTrace() LeveledLogger }
LeveledLogger interface for logging by level
func StackTrace ¶
func StackTrace() LeveledLogger
StackTrace creates a new log Entry with pre-populated field with stack trace.
func WithFields ¶
func WithFields(fields ...Field) LeveledLogger
WithFields returns a log Entry with fields set
type TraceEntry ¶
type TraceEntry struct {
// contains filtered or unexported fields
}
TraceEntry is an object used in creating a trace log entry