xlog

package
v0.0.0-...-ed9fe1d Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2018 License: BSD-3-Clause Imports: 12 Imported by: 0

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

Examples

Constants

This section is empty.

Variables

View Source
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.

View Source
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.

View Source
var NullSink = &nullSink{}

NullSink is a sink to write nothing.

View Source
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`.

func SetOption

func SetOption(o *Option)

SetOption sets the option for the global logger

func SetSink

func SetSink(s Sink)

SetSink sets the default logger sink.

Types

type Filter

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

Filter is a Sink to write records by condition to the next sink.

func (*Filter) Write

func (f *Filter) Write(r *Record) error

Write implements `Sink#Write`

type FilterFunc

type FilterFunc func(r *Record) bool

FilterFunc

func (FilterFunc) Pipe

func (f FilterFunc) Pipe(s Sink) *Filter

Pipe returns a *Filter that writes to Sink using FilterFunc

type Formatter

type Formatter interface {
	Format(*Record) ([]byte, error)
}

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 NewIOSink

func NewIOSink(w io.Writer) *IOSink

NewIOSink returns a IOSink for w.

func NewIOSinkWithFormatter

func NewIOSinkWithFormatter(w io.Writer, f Formatter) *IOSink

NewIOSinkWithFormatter returns a IOSink for w with f Formatter

func (*IOSink) Write

func (s *IOSink) Write(r *Record) error

Write implements Sink#Write

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 MustParseLevel(s string) Level

func ParseLevel

func ParseLevel(s string) (Level, error)

func ParseLevelOr

func ParseLevelOr(s string, or Level) Level

func (Level) Filter

func (l Level) Filter(s Sink) Sink

Filter returns a Sink that filter records whose level is >= l

func (Level) MarshalJSON

func (i Level) MarshalJSON() ([]byte, error)

func (Level) String

func (i Level) String() string

func (*Level) UnmarshalJSON

func (i *Level) UnmarshalJSON(b []byte) error

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 New

func New(s Sink) *Logger

New returns a new Logger instance.

func WithContext

func WithContext(ctx context.Context, prefix string) (context.Context, *Logger)

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 WithKey

func WithKey(name string) *Logger

WithKey returns a shallow copy of global Logger with its name changed to name.

func (*Logger) Debug

func (l *Logger) Debug(v interface{})

Debug to write data log with LevelDebug

func (*Logger) Debugf

func (l *Logger) Debugf(s string, v ...interface{})

Debugf to write text log with LevelDebug

func (*Logger) Error

func (l *Logger) Error(v interface{})

Error to write data log with LevelError

func (*Logger) Errorf

func (l *Logger) Errorf(s string, v ...interface{})

Errorf to write text log with LevelError

func (*Logger) Fatal

func (l *Logger) Fatal(v interface{})

Fatal to write text log with LevelFatal

func (*Logger) Fatalf

func (l *Logger) Fatalf(s string, v ...interface{})

Fatalf to write text log with LevelTrace

func (*Logger) Info

func (l *Logger) Info(v interface{})

Info to write data log with LevelInfo

func (*Logger) Infof

func (l *Logger) Infof(s string, v ...interface{})

Infof to write text log with LevelInfo

func (*Logger) Trace

func (l *Logger) Trace(v interface{})

Trace to write data log with LevelTrace

func (*Logger) Tracef

func (l *Logger) Tracef(s string, v ...interface{})

Tracef to write text log with LevelTrace

func (*Logger) Warn

func (l *Logger) Warn(v interface{})

Warn to write data log with LevelWarn

func (*Logger) Warnf

func (l *Logger) Warnf(s string, v ...interface{})

Warnf to write text log with LevelWarn

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Logger

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

func (*Logger) WithKey

func (l *Logger) WithKey(key interface{}) *Logger

WithKey returns a shallow copy of Logger with its key changed to `key`.

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

func (*Printer) Printf

func (p *Printer) Printf(s string, v ...interface{})

Printf to format printf style.

func (*Printer) Println

func (p *Printer) Println(v ...interface{})

Println to format println style.

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) Context

func (r *Record) Context() context.Context

Context returns context.Context associated with the record.

func (*Record) ContextValue

func (r *Record) ContextValue(key interface{}) interface{}

ContextValue returns the context value

type Sink

type Sink interface {
	Write(*Record) error // Write a record to the destination
}

Sink is an interface for log destination

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.

Directories

Path Synopsis
Package xlogtest for internal tests.
Package xlogtest for internal tests.

Jump to

Keyboard shortcuts

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