slago

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2020 License: Apache-2.0 Imports: 17 Imported by: 3

README

slago

Simple Logging Abstraction for Go. Slago provides bridge and binder for logger which can sent log from logger to another logger you preferred. Slago also provides unified writers, encoders and filters, it brings different logger with same apis and configurations.

Usage

  • Add logger you want to bind to:
slago.Bind(salzero.NewZeroLogger())
  • Install the bridges for other logger :
slago.Install(bridge.NewLogBridge())
slago.Install(bridge.NewLogrusBridge())
slago.Install(bridge.NewZapBrige())
  • Configure the output writer:
cw := slago.NewConsoleWriter(func(o *slago.ConsoleWriterOption) {
		o.Encoder = slago.NewPatternEncoder(
			"#color(#date{2006-01-02T15:04:05.000Z07:00}){cyan} #color(" +"#level) #message #fields")
	})
slago.Logger().AddWriter(cw)
fw := slago.NewFileWriter(func(o *slago.FileWriterOption) {
		o.Encoder = slago.NewJsonEncoder()
		o.Filter = slago.NewLevelFilter(slago.TraceLevel)
		o.Filename = "slago-test.log"
		o.RollingPolicy = slago.NewSizeAndTimeBasedRollingPolicy(
			func(o *slago.SizeAndTimeBasedRPOption) {
				o.FilenamePattern = "slago-archive.#date{2006-01-02}.#index.log"
				o.MaxFileSize = "10MB"
			})
	})
slago.Logger().AddWriter(fw)
  • Add logging...:
slago.Logger().Trace().Msg("slago")
slago.Logger().Info().Int("int", 88).Interface("slago", "val").Msg("")
  • If you log with other logger, it will send to the bound logger:
zap.L().With().Warn("this is zap")
log.Printf("this is builtin logger")

Note: only global logger will send log to bound logger if using logger like zap or zerolog or other loggers.

License

Copyright (c) 2019-2020 Anbillon Team (anbillonteam@gmail.com).

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Documentation

Index

Constants

View Source
const (
	LevelFieldKey     = "level"
	TimestampFieldKey = "time"
	MessageFieldKey   = "message"
	LoggerFieldKey    = "logger_name"

	TimestampFormat = time.RFC3339Nano

	Slash = "/"
)
View Source
const (
	DefaultLayout = "#color(#date{2006-01-02 15:04:05}){cyan} " +
		"#color(#level) #message #fields"
)
View Source
const RootLoggerName = "ROOT"

Variables

This section is empty.

Functions

func Bind

func Bind(logger SlaLogger)

Bind binds an implementation of slago logger as output logger.

func BrigeWrite

func BrigeWrite(bridge Bridge, p []byte) error

BrigeWrite writes data from bridge to slago logger.

func Install

func Install(bridge Bridge)

Install installs a logging framework bridge into slago. All the log of the bridge will be delegated to slagto if the logging framework bridge was installed.

func NewBlockingQueue

func NewBlockingQueue(capacity int) *blockingQueue

NewBlockingQueue creates a new blocking queue.

func NewPatternCompiler

func NewPatternCompiler(node *node, converterMap map[string]NewConverter) *patternCompiler

NewPatternCompiler creates a new instance of pattern compiler.

func NewPatternParser

func NewPatternParser(pattern string) *patternParser

NewPatternParser creates a new instance of pattern parser.

func ReplaceJson added in v0.4.0

func ReplaceJson(p []byte, buf *bytes.Buffer, searchKey string,
	transform func(k, v []byte) (nk, kv []byte, e error)) error

ReplaceJson replaces key/value with given search key.

func Report

func Report(msg string)

Report reports message in stdou

func Reportf

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

Reportf reports message with arguments in stdou

func ReportfExit

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

ReportfExit reportes message with arguments in stdout and exit process.

Types

type AsyncWriterOption added in v0.4.0

type AsyncWriterOption struct {
	Ref       Writer
	QueueSize int
}

AsyncWriterOption represents available options for async writer.

type Bridge

type Bridge interface {
	// Name returns the name of this bridge.
	Name() string

	// ParseLevel parses the given level string into slago level.
	ParseLevel(lvl string) Level
}

Bridge represents bridge between other logging framework and slago logger.

type ConsoleWriterOption

type ConsoleWriterOption struct {
	Encoder Encoder
	Filter  Filter
}

ConsoleWriterOption represents available options for console writer.

type Converter

type Converter interface {
	// AttatchNext attatches next converter to the chain.
	AttatchNext(next Converter)

	// Next gets next from the chain.
	Next() Converter

	// AttachChild attaches child converter to current converter.
	AttachChild(child Converter)

	// AttachOptions attaches options to current converter.
	AttachOptions(opts []string)

	// Convert converts given data into buffer.
	Convert(origin interface{}, buf *bytes.Buffer)
}

Converter represents a pattern converter which will convert pattern to string.

func NewLiteralConverter

func NewLiteralConverter(value string) Converter

type Encoder

type Encoder interface {
	// Encode encodes origin data to formatted data.
	Encode(e *LogEvent) (data []byte, err error)
}

Encoder represents an encoder to encode logging event into different format.

func NewJsonEncoder

func NewJsonEncoder() Encoder

NewJsonEncoder creates a new instance of encoder to encode data to json.

func NewPatternEncoder

func NewPatternEncoder(options ...func(*PatternEncoderOption)) Encoder

NewPatternEncoder creates a new instance of pattern encoder.

type FileWriterOption

type FileWriterOption struct {
	Filter        Filter
	Encoder       Encoder
	RollingPolicy RollingPolicy
	Filename      string
}

FileWriterOption represents available options for file writer.

type Filter

type Filter interface {
	// Do filters the logging. True means filterd, otherwise pass through.
	Do(e *LogEvent) bool
}

Filter represents a logging filter for slago.

func NewKeywordFilter added in v0.4.0

func NewKeywordFilter(keywords ...string) Filter

NewKeywordFilter creates a new instance of keywordFilter.

func NewLevelFilter

func NewLevelFilter(lvl Level) Filter

NewLevelFilter creates a new instance of levelFilter.

type Level

type Level int8
const (
	TraceLevel Level = iota
	DebugLevel
	InfoLevel
	WarnLevel
	ErrorLevel
	FatalLevel
	PanicLevel
)

func ParseLevel

func ParseLevel(lvl string) Level

ParseLevel converts a level string into slago level value.

func (Level) String

func (l Level) String() string

type Lifecycle added in v0.4.0

type Lifecycle interface {
	// Start the component.
	Start()
	// Stop the component.
	Stop()
}

Lifecycle represents the lifecycle of component.

type LogEvent added in v0.4.0

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

func (*LogEvent) Fields added in v0.4.0

func (e *LogEvent) Fields(callback func(k, v []byte, isString bool) error) error

Fields gets extra key and value bytes.

func (*LogEvent) Level added in v0.4.0

func (e *LogEvent) Level() []byte

Level returns level string bytes.

func (*LogEvent) LevelInt added in v0.4.0

func (e *LogEvent) LevelInt() Level

LevelInt returns level int value.

func (*LogEvent) Logger added in v0.4.0

func (e *LogEvent) Logger() []byte

Logger return logger name bytes.

func (*LogEvent) Message added in v0.4.0

func (e *LogEvent) Message() []byte

Message returns message bytes.

func (*LogEvent) Time added in v0.4.0

func (e *LogEvent) Time() []byte

Time returns rfc3339nano bytes.

type MultiWriter

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

MultiWriter represents multiple writer which implements slago.Writer. This writer is used as output which will implement SlaLogger.

func NewMultiWriter

func NewMultiWriter() *MultiWriter

NewMultiWriter creates a new multiple writer.

func (*MultiWriter) AddWriter

func (mw *MultiWriter) AddWriter(writers ...Writer)

AddWriter adds a slago writer into multi writer.

func (*MultiWriter) Reset

func (mw *MultiWriter) Reset()

Reset will remove all writers.

func (*MultiWriter) Write

func (mw *MultiWriter) Write(p []byte) (n int, err error)

type NewConverter

type NewConverter func() Converter

type PatternEncoderOption added in v0.4.0

type PatternEncoderOption struct {
	Layout     string
	Converters map[string]NewConverter
}

type Record

type Record interface {
	// Str adds string value to this record.
	Str(key, val string) Record

	// Strs adds string array value to this record.
	Strs(key string, val []string) Record

	// Bytes adds byte array value to this record.
	Bytes(key string, val []byte) Record

	// Hex adds hex byte array value to this record.
	Hex(key string, val []byte) Record

	// Err adds err to this record.
	Err(err error) Record

	// Errs adds err array to this record.
	Errs(key string, errs []error) Record

	// Bool adds bool value to this record.
	Bool(key string, val bool) Record

	// Bools adds bool array value to this record.
	Bools(key string, val []bool) Record

	// Int adds int value to this record.
	Int(key string, val int) Record

	// Ints adds int array value to this record.
	Ints(key string, val []int) Record

	// Int8 adds int8 value to this record.
	Int8(key string, val int8) Record

	// ints8 adds int8 array value to this record.
	Ints8(key string, val []int8) Record

	// Int16 adds int16 value to this record.
	Int16(key string, val int16) Record

	// Ints16 adds int16 array value to this record.
	Ints16(key string, val []int16) Record

	// Int32 adds int32 value to this record.
	Int32(key string, val int32) Record

	// Int32 adds int32 array value to this record.
	Ints32(key string, val []int32) Record

	// Int64 adds int64 value to this record.
	Int64(key string, val int64) Record

	// Int64 adds int64 array value to this record.
	Ints64(key string, val []int64) Record

	// Uint adds uint value to this record.
	Uint(key string, val uint) Record

	// Uints adds uint array value to this record.
	Uints(key string, val []uint) Record

	// Uint8 adds uint8 value to this record.
	Uint8(key string, val uint8) Record

	// Uints8 adds uint8 array value to this record.
	Uints8(key string, val []uint8) Record

	// Uint16 adds uint16 value to this record.
	Uint16(key string, val uint16) Record

	// Uints16 adds uint16 array value to this record.
	Uints16(key string, val []uint16) Record

	// Uint32 adds uint32 value to this record.
	Uint32(key string, val uint32) Record

	// Uint32 adds uint32 array value to this record.
	Uints32(key string, val []uint32) Record

	// Uint64 adds uint64 value to this record.
	Uint64(key string, val uint64) Record

	// Uints64 adds uint64 array value to this record.
	Uints64(key string, val []uint64) Record

	// Float32 adds float32 value to this record.
	Float32(key string, val float32) Record

	// Floats32 adds float32 array value to this record.
	Floats32(key string, val []float32) Record

	// Float64 adds float64 value to this record.
	Float64(key string, val float64) Record

	// Floats64 adds float64 array value to this record.
	Floats64(key string, val []float64) Record

	// Time adds time value to this record.
	Time(key string, val time.Time) Record

	// Times adds time array value to this record.
	Times(key string, val []time.Time) Record

	// Dur adds duration value to this record.
	Dur(key string, val time.Duration) Record

	// Time adds duration array value to this record.
	Durs(key string, val []time.Duration) Record

	// Interface adds interface value to this record.
	Interface(key string, val interface{}) Record

	// Msg adds a message to this record and output log.
	Msg(msg string)

	// Msgf adds a message with format to this record and output log.
	Msgf(format string, v ...interface{})
}

Record represents a log record to hold the data to log.

type RollingPolicy

type RollingPolicy interface {
	// Prepare prepares current rolling policy
	Prepare() error

	// Attach attaches file writer.
	Attach(w *fileWriter)

	// ShouldTrigger check if there's necessary to trigger rolling.
	ShouldTrigger(fileSize int64) bool

	// Rotate does the log rolling.
	Rotate() error
}

RollingPolicy represents policy for log rolling.

func NewNoopRollingPolicy added in v0.4.0

func NewNoopRollingPolicy() RollingPolicy

NewNoopRollingPolicy creates a new instance of noop rolling policy which will do nothing.

func NewSizeAndTimeBasedRollingPolicy

func NewSizeAndTimeBasedRollingPolicy(options ...func(
	*SizeAndTimeBasedRPOption)) RollingPolicy

NewSizeAndTimeBasedRollingPolicy creates a new instance of size and time based rolling policy for file writer.

func NewTimeBasedRollingPolicy

func NewTimeBasedRollingPolicy(filenamePattern string) RollingPolicy

NewTimeBasedRollingPolicy creates a instance of time based rolling policy for file writer.

type SizeAndTimeBasedRPOption

type SizeAndTimeBasedRPOption struct {
	FilenamePattern string
	MaxFileSize     string
}

SizeAndTimeBasedRPOption represents available options for size and time based rolling policy.

type SlaLogger

type SlaLogger interface {
	// Name returns the name of current slago logger implementation.
	Name() string

	// AddWriter add one or more writer to this logger.
	AddWriter(w ...Writer)

	// ResetWriter will remove all writers added before.
	ResetWriter()

	// SetLevel sets global level for root logger.
	SetLevel(lvl Level)

	// Trace logs with trace level.
	Trace() Record

	// Debug logs with debug level.
	Debug() Record

	// Info logs with info level.
	Info() Record

	// Warn logs with warn level.
	Warn() Record

	// Error logs with error level.
	Error() Record

	// Fatal logs with faltal level.
	Fatal() Record

	// Panic logs with panic level.
	Panic() Record

	// WriteRaw writes raw logging event.
	WriteRaw(p []byte)
}

SlaLogger represents a logging abstraction.

func Logger

func Logger(name ...string) SlaLogger

Logger get a global slago logger to use. The name will only get the first one.

type SocketReader

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

func NewSocketReader

func NewSocketReader() *SocketReader

NewSocketReader creates a new instance of socket reader.

func (*SocketReader) Start

func (sr *SocketReader) Start()

func (*SocketReader) Stop

func (sr *SocketReader) Stop()

type SocketWriterOption

type SocketWriterOption struct {
	RemoteUrl         *url.URL
	QueueSize         int
	ReconnectionDelay time.Duration
	Filter            Filter
}

type Writer

type Writer interface {
	io.Writer

	// Encoder returns encoder used in current writer.
	Encoder() Encoder

	// Filter returns filter used in current writer.
	Filter() Filter
}

Writer is the interface that wraps the io.Writer, add adds Encoder and Filter func for slago to ecnode and filter logs.

func NewAsyncWriter

func NewAsyncWriter(options ...func(*AsyncWriterOption)) Writer

NewAsyncWriter creates a new instance of asynchronous writer.

func NewConsoleWriter

func NewConsoleWriter(options ...func(*ConsoleWriterOption)) Writer

NewConsoleWriter creates a new instance of console writer.

func NewFileWriter

func NewFileWriter(options ...func(*FileWriterOption)) Writer

NewFileWriter creates a new instance of file writer.

func NewSocketWriter

func NewSocketWriter(options ...func(*SocketWriterOption)) Writer

NewSocketWriter create a logging writter via socket.

Directories

Path Synopsis
binder
log-to-slago module
slago-api module
zap-to-slago module

Jump to

Keyboard shortcuts

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