Documentation ¶
Overview ¶
Package xlog provides extended utility functions for log
Package xlog provides the logging framework for applications.
Logger is a top level struct that writes any type of log data to Sink.
* Name
Each of Logger should have it's name to identify which log records are sent by which logger. By default, that name is automatically resolved by the package name.
* Level and lazy formatting
As other logging frameworks do, xlog supports logging level support.And we support lazy evaluated logging.
logger.Debug(func(fmt *Printer){ result := somethingHeavy() fmt.Println(result) })
In this semantic, somethingHeavy() is a heavy workload and only executed if minimum filter level is under Debug. If the level is upper than Debug, the heavy workload is not executed so that the logging cost will be reduced.
* Pipeline
Sink is an interface that implements `Write(*Record) error` and it's easy to make a pipeline from a Sink to another Sink. Filter is a such kind of Sink that creats pipeline for filtering records.
* Context
Logger can be aware of context.Context (even we support "context") You can associate any context by *Logger.WithContext() and write it by `{{context key .}}`
Index ¶
- Variables
- func SetKeyFilter(key interface{}, level Level)
- func SetOption(o *Option)
- func SetSink(s Sink)
- type Filter
- type FilterFunc
- type Formatter
- type IOSink
- type Level
- type Logger
- func (l *Logger) Debug(v interface{})
- func (l *Logger) Debugf(s string, v ...interface{})
- func (l *Logger) Error(v interface{})
- func (l *Logger) Errorf(s string, v ...interface{})
- func (l *Logger) Fatal(v interface{})
- func (l *Logger) Fatalf(s string, v ...interface{})
- func (l *Logger) Info(v interface{})
- func (l *Logger) Infof(s string, v ...interface{})
- func (l *Logger) Trace(v interface{})
- func (l *Logger) Tracef(s string, v ...interface{})
- func (l *Logger) Warn(v interface{})
- func (l *Logger) Warnf(s string, v ...interface{})
- func (l *Logger) WithContext(ctx context.Context) *Logger
- func (l *Logger) WithKey(key interface{}) *Logger
- type Option
- type Printer
- type Record
- type Sink
- type TextFormatter
- func (f *TextFormatter) Format(r *Record) ([]byte, error)
- func (f *TextFormatter) SetCode(code ansi.Code) *TextFormatter
- func (f *TextFormatter) SetDebug(s string, code ansi.Code) *TextFormatter
- func (f *TextFormatter) SetError(s string, code ansi.Code) *TextFormatter
- func (f *TextFormatter) SetFatal(s string, code ansi.Code) *TextFormatter
- func (f *TextFormatter) SetInfo(s string, code ansi.Code) *TextFormatter
- func (f *TextFormatter) SetTrace(s string, code ansi.Code) *TextFormatter
- func (f *TextFormatter) SetWarn(s string, code ansi.Code) *TextFormatter
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var KeyLevelFilter = func(keyLevels map[interface{}]Level, l Level) FilterFunc { return func(r *Record) bool { if lvl, ok := keyLevels[r.LoggerKey]; ok { return r.Level >= lvl } return r.Level >= l } }
KeyLevelFilter is like LevelFilter but more flexible by key matching. If key is not found in `keyLevels`, default level l is used as fallback.
var LevelFilter = func(min Level) FilterFunc { return func(r *Record) bool { return r.Level >= min } }
LevelFilter is FilterFunc that filter records whose level is under the given level.
var NullSink = &nullSink{}
NullSink is a sink to write nothing.
var StdLogSink = &stdLogSink{}
StdLogSink is a sink to write logs with log.Printf()
Functions ¶
func SetKeyFilter ¶
func SetKeyFilter(key interface{}, level Level)
SetKeyFilter sets the specific filter level for `key`.
Types ¶
type Filter ¶
type Filter struct {
// contains filtered or unexported fields
}
Filter is a Sink to write records by condition to the next sink.
type FilterFunc ¶
FilterFunc
func (FilterFunc) Pipe ¶
func (f FilterFunc) Pipe(s Sink) *Filter
Pipe returns a *Filter that writes to Sink using FilterFunc
type Formatter ¶
Formatter is an inerface to convert *Record to []byte
Example ¶
formatter := NewTextFormatter( `{{formattimestamp .}} [{{.Level}}] {{.Data}}`, ) formatter.SetError( `{{formattimestamp .}} [{{.Level}}] {{.Data}}{{formatstack .}}`, ansi.Reset, ) logger := New(NewIOSinkWithFormatter(os.Stdout, formatter)) xtime.RunAt( time.Date(2016, 1, 1, 12, 10, 25, 0, time.UTC), func() { logger.Errorf("This is a log") }, ) // Do not run tests since line number may differ in each environment. // Sample output is like follows: // // 2016-01-01T12:10:25Z [error] This is a log // github.com/speedland/go/x/xlog.ExampleLoggerWithConfigurationByLevel.func1 (at github.com/speedland/go/x/xlog/xlog_test.go#75) // github.com/speedland/go/x/xtime.RunAt (at github.com/speedland/go/x/xtime/xtime.go#33) // github.com/speedland/go/x/xlog.ExampleLoggerWithConfigurationByLevel (at github.com/speedland/go/x/xlog/xlog_test.go#82)
Output:
type IOSink ¶
type IOSink struct {
// contains filtered or unexported fields
}
IOSink is an implementation of Sink that write log to io.Writer.
func NewIOSinkWithFormatter ¶
NewIOSinkWithFormatter returns a IOSink for w with f Formatter
type Level ¶
type Level int
Level is a enum for log Level
const ( LevelAll Level = iota LevelTrace LevelDebug LevelInfo LevelWarn LevelError LevelFatal LevelNone )
Available Level values
func MustParseLevel ¶
func ParseLevel ¶
func ParseLevelOr ¶
func (Level) MarshalJSON ¶
func (*Level) UnmarshalJSON ¶
type Logger ¶
type Logger struct { *Option // contains filtered or unexported fields }
Logger the logger
Example ¶
formatter := NewTextFormatter( `{{formattimestamp .}} [{{.Level}}] {{.Data}}`, ) logger := New( NewIOSinkWithFormatter(os.Stdout, formatter), ) xtime.RunAt( time.Date(2016, 1, 1, 12, 10, 25, 0, time.UTC), func() { logger.Infof("This is a log") logger.Info(&T{"1"}) }, )
Output: 2016-01-01T12:10:25Z [info] This is a log 2016-01-01T12:10:25Z [info] T{1}
Example (WithLevelFilter) ¶
formatter := NewTextFormatter( `{{formattimestamp .}} [{{.Level}}] {{.Data}}`, ) logger := New( LevelInfo.Filter( NewIOSinkWithFormatter(os.Stdout, formatter), ), ) xtime.RunAt( time.Date(2016, 1, 1, 12, 10, 25, 0, time.UTC), func() { logger.Infof("This is a log") logger.Debugf("DEBUGDEBUGDEBUG") }, )
Output: 2016-01-01T12:10:25Z [info] This is a log
func WithContext ¶
WithContext returns a shallow copy of global Logger with its context changed to ctx.
func WithContextAndKey ¶
func WithContextAndKey(ctx context.Context, prefix string, key interface{}) (context.Context, *Logger)
WithContextAndKey returns a shallow copy of global Logger with its context changed to ctx and bound with `key`
func (*Logger) Debug ¶
func (l *Logger) Debug(v interface{})
Debug to write data log with LevelDebug
func (*Logger) Error ¶
func (l *Logger) Error(v interface{})
Error to write data log with LevelError
func (*Logger) Fatal ¶
func (l *Logger) Fatal(v interface{})
Fatal to write text log with LevelFatal
func (*Logger) Trace ¶
func (l *Logger) Trace(v interface{})
Trace to write data log with LevelTrace
func (*Logger) WithContext ¶
WithContext returns a shallow copy of Logger with its context changed to ctx. The provided ctx must be non-nil.
Example ¶
formatter := NewTextFormatter( `{{formattimestamp .}} [{{.Level}}] [{{.ContextValue "id"}}] {{.Data}}`, ) logger := New( NewIOSinkWithFormatter(os.Stdout, formatter), ) xtime.RunAt( time.Date(2016, 1, 1, 12, 10, 25, 0, time.UTC), func() { logger.Errorf("This is a log") ctx := context.Background() ctx = context.WithValue(ctx, "id", "123") logger = logger.WithContext(ctx) logger.Errorf("This is a log") }, )
Output: 2016-01-01T12:10:25Z [error] [<no value>] This is a log 2016-01-01T12:10:25Z [error] [123] This is a log
type Option ¶
type Option struct { MinStackCaptureOn Level // Minimum Level where logger captures stacks. Strongly recommend to set LevelFatal. StackCaptureDepth int // # of stack frames to be captured on logging. }
Option is option fields for logger.
type Printer ¶
type Printer struct {
// contains filtered or unexported fields
}
Printer is a temporary object to generate a log text within lazy formatting context.
Example ¶
formatter := NewTextFormatter( `{{formattimestamp .}} [{{.Level}}] {{.Data}}`, ) loggerInfo := New( LevelFilter(LevelInfo).Pipe( NewIOSinkWithFormatter(os.Stdout, formatter), ), ) loggerDebug := New( LevelFilter(LevelDebug).Pipe( NewIOSinkWithFormatter(os.Stdout, formatter), ), ) var f = func(fmt *Printer) { // This is not be executed. fmt.Printf("foo") } xtime.RunAt( time.Date(2016, 1, 1, 12, 10, 25, 0, time.UTC), func() { loggerInfo.Debug(f) loggerDebug.Debug(f) }, )
Output: 2016-01-01T12:10:25Z [debug] foo
type Record ¶
type Record struct { Timestamp time.Time Data interface{} Level Level // Log Levell LoggerKey interface{} // Logger Key Stack []*xruntime.Frame // Log Source BenchmarkLoggerFewStackCapture // contains filtered or unexported fields }
Record is a data set for one log line/data
func (*Record) ContextValue ¶
func (r *Record) ContextValue(key interface{}) interface{}
ContextValue returns the context value
type TextFormatter ¶
type TextFormatter struct {
// contains filtered or unexported fields
}
TextFormatter is an implementation of Formatter using text.Template
func NewTextFormatter ¶
func NewTextFormatter(t string) *TextFormatter
NewTextFormatter returns a new *TextFormatter by given template string with default funcMap. You can define `t` as a normal "text/template".Template with *Record data. For example
NewTextFormatter("{{.SourceLine}}")
formats *Record to *Record.SourceLine.
The `Data`` field is formatted by using String() function ¶
Following functions are available in the template and you can add/override custom functions by `NewTextFormatterWithFuncs“
formattimestamp function to format .Timestamp field to string. By default, time.RFC3339 format is used.
formatstack function to format .Stack field to string. By default, All of stack frames are rendered.
func NewTextFormatterWithFuncs ¶
func NewTextFormatterWithFuncs(s string, funcMap template.FuncMap) *TextFormatter
NewTextFormatterWithFuncs is like NewTextFormatter with adding/overriding custom funcions in the template.
func (*TextFormatter) Format ¶
func (f *TextFormatter) Format(r *Record) ([]byte, error)
Format immplements Formatter#Format(*Record)
func (*TextFormatter) SetCode ¶
func (f *TextFormatter) SetCode(code ansi.Code) *TextFormatter
SetCode sets the default ANSI code for log texts
func (*TextFormatter) SetDebug ¶
func (f *TextFormatter) SetDebug(s string, code ansi.Code) *TextFormatter
SetDebug set the template for LevelDebug logs.
func (*TextFormatter) SetError ¶
func (f *TextFormatter) SetError(s string, code ansi.Code) *TextFormatter
SetError set the template for LevelError logs.
func (*TextFormatter) SetFatal ¶
func (f *TextFormatter) SetFatal(s string, code ansi.Code) *TextFormatter
SetFatal set the template for LevelFatal logs.
func (*TextFormatter) SetInfo ¶
func (f *TextFormatter) SetInfo(s string, code ansi.Code) *TextFormatter
SetInfo set the template for LevelInfo logs.
func (*TextFormatter) SetTrace ¶
func (f *TextFormatter) SetTrace(s string, code ansi.Code) *TextFormatter
SetTrace set the template for LevelTrace logs.
func (*TextFormatter) SetWarn ¶
func (f *TextFormatter) SetWarn(s string, code ansi.Code) *TextFormatter
SetWarn set the template for LevelWarn logs.