lork

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: May 29, 2023 License: Apache-2.0 Imports: 24 Imported by: 7

README

lork

The flexible, extensible and structured logging for Go. Lork provides bridge and binder for logger which can send log from logger to another logger you preferred. Lork also provides unified writers, encoders and filters, it brings different logger with same apis and flexible configurations.

Features

  • Logging with zero allocation
  • Multiple writer
  • Multiple structured format
  • Flexible configurations

Usage

Look at this tutorial

Benchmarks

Benchmarks with complex log field, different encoder and writer.

cpu: Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
BenchmarkJsonFileWriter-8      	  290490        3615 ns/op      0 B/op      0 allocs/op
BenchmarkPatternFileWriter-8   	  243361        4670 ns/op      0 B/op      0 allocs/op
BenchmarkAsyncFileWriter-8     	 1220036        998.8 ns/op     0 B/op      0 allocs/op
BenchmarkNoWriter-8            	 1591646        746.5 ns/op     0 B/op      0 allocs/op

Credits

  • slf4j: Simple Logging Facade for Java
  • logback: The reliable, generic, fast and flexible logging framework for Java.

Donate

If you enjoy this project and want to support it, you can buy a coffee. ❤

Buy Me A Coffee

License

Copyright (c) 2019-2023 Vincent Cheung (coolingfall@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"
	LoggerNameFieldKey = "logger_name"
	ErrorFieldKey      = "error"

	TimestampFormat   = time.RFC3339Nano
	TimeFormatRFC3339 = "2006-01-02T15:04:05.000Z07:00"

	RootLoggerName = "ROOT"
)
View Source
const (
	DefaultPattern = "#color(#date{2006-01-02T15:04:05.000}){cyan} #color(#level) " +
		"#color([#logger]){magenta} : #message #fields"
)
View Source
const DefaultQueueSize = 512

Variables

This section is empty.

Functions

func BridgeWrite

func BridgeWrite(bridge Bridge, p []byte)

BridgeWrite writes data from bridge to lork logger.

func Install

func Install(bridge Bridge)

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

func Load added in v0.7.0

func Load(provider Provider)

Load loads an implementation of lork provider.

func NewLogBridge

func NewLogBridge(options ...func(*LogBridgeOption)) *logBridge

NewLogBridge creates a new lork bridge for standard log.

func PackageName

func PackageName(skip int) string

PackageName get the package name of caller.

func ReplaceJson

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 stdout

func Reportf

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

Reportf reports message with arguments in stdout

func ReportfExit

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

ReportfExit reports message with arguments in stdout and exit process.

func Reset added in v0.7.0

func Reset()

Reset will reset all providers and stop writers.

Types

type ArchiveRemover

type ArchiveRemover interface {
	// MaxHistory sets max history for logs.
	MaxHistory(max int)

	// CleanAsync cleans logs asynchronously with given time.
	CleanAsync(now time.Time)
}

ArchiveRemover represents a remover which removes archived logs.

type Archiver

type Archiver interface {
	// Archive makes an archiver with given filename and archive filename.
	Archive(filename, archiveFilename string) error
}

type AsyncWriter added in v0.7.0

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

func NewAsyncWriter

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

NewAsyncWriter creates a new instance of asynchronous writer.

func (*AsyncWriter) AddWriter added in v0.7.0

func (w *AsyncWriter) AddWriter(writers ...Writer)

func (*AsyncWriter) Attached added in v0.7.0

func (w *AsyncWriter) Attached(writer Writer) bool

func (*AsyncWriter) DoWrite added in v0.7.0

func (w *AsyncWriter) DoWrite(event *LogEvent) error

func (*AsyncWriter) GetWriter added in v0.7.0

func (w *AsyncWriter) GetWriter(name string) Writer

func (*AsyncWriter) Name added in v0.7.0

func (w *AsyncWriter) Name() string

func (*AsyncWriter) ResetWriter added in v0.7.0

func (w *AsyncWriter) ResetWriter()

func (*AsyncWriter) Start added in v0.7.0

func (w *AsyncWriter) Start()

func (*AsyncWriter) Stop added in v0.7.0

func (w *AsyncWriter) Stop()

type AsyncWriterOption

type AsyncWriterOption struct {
	Name      string
	QueueSize int
}

AsyncWriterOption represents available options for async writer.

type BaseProvider added in v0.7.0

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

BaseProvider is a base Provider with rich features.

func NewBaseProvider added in v0.7.0

func NewBaseProvider(ctx *LoggerContext) *BaseProvider

NewBaseProvider creates a new BaseProvider.

func (*BaseProvider) LoggerFactory added in v0.7.0

func (p *BaseProvider) LoggerFactory() ILoggerFactory

func (*BaseProvider) Name added in v0.7.0

func (p *BaseProvider) Name() string

func (*BaseProvider) Prepare added in v0.7.0

func (p *BaseProvider) Prepare()

type BlockingQueue added in v0.7.0

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

func NewBlockingQueue

func NewBlockingQueue(capacity int) *BlockingQueue

NewBlockingQueue creates a new blocking queue.

func (*BlockingQueue) Clear added in v0.7.0

func (q *BlockingQueue) Clear()

Clear clears the data in queue and reset all index.

func (*BlockingQueue) Len added in v0.7.0

func (q *BlockingQueue) Len() int

Len gets the count in current queue.

func (*BlockingQueue) Put added in v0.7.0

func (q *BlockingQueue) Put(item interface{})

Put puts an item into queue.

func (*BlockingQueue) RemainCapacity added in v0.7.0

func (q *BlockingQueue) RemainCapacity() int

RemainCapacity gets remain capacity in queue.

func (*BlockingQueue) Take added in v0.7.0

func (q *BlockingQueue) Take() interface{}

Take takes an item from queue.

type Bridge

type Bridge interface {
	Nameable

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

Bridge represents bridge between other logging framework and lork logger.

type BytesWriter added in v0.7.0

type BytesWriter interface {
	io.Writer

	Nameable

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

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

BytesWriter represents a writer which will write bytes with Encoder and Filter. Create Writer with NewBytesWriter if writer implemented BytesWriter.

type Configurator added in v0.7.0

type Configurator interface {
	// Configure will configure the logger with writers and return ExecutionStatus.
	Configure(ctx *LoggerContext) ExecutionStatus
}

Configurator represents a configurator for logger.

type ConsoleWriterOption

type ConsoleWriterOption struct {
	Name    string
	Encoder Encoder
	Filter  Filter
}

ConsoleWriterOption represents available options for console writer.

type Converter

type Converter interface {
	// AttachNext attaches next converter to the chain.
	AttachNext(next Converter)

	// Next will get next converter 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 EventRecorder added in v0.7.0

type EventRecorder interface {
	// WriteEvent write LogEvent.
	WriteEvent(event *LogEvent) error
}

EventRecorder represents a recorder to record LogEvent.

type EventWriter

type EventWriter interface {
	Nameable

	// Write Writes given event.
	Write(event *LogEvent) error

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

	// Synchronized should this writer write data synchronously or not.
	Synchronized() bool
}

EventWriter represents writer which will write raw LogEvent with filter. Create Writer with NewEventWriter if writer implemented EventWriter.

type ExecutionStatus added in v0.7.0

type ExecutionStatus int8
const (
	StatusNeutral ExecutionStatus = iota
	StatusNext
	StatusNoNext
)

type FileWriterOption

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

FileWriterOption represents available options for file writer.

type Filter

type Filter interface {
	// Do filters the logging. The logs will be accepted or denied according to FilterReply.
	Do(e *LogEvent) FilterReply
}

Filter represents a logging filter for lork.

func NewKeywordFilter

func NewKeywordFilter(keywords ...string) Filter

NewKeywordFilter creates a new instance of keywordFilter.

func NewThresholdFilter

func NewThresholdFilter(lvl Level) Filter

NewThresholdFilter creates a new instance of thresholdFilter.

type FilterReply

type FilterReply int8

FilterReply defines the result of filter.

const (
	// Accept represents the logging will be accepted by filter.
	Accept FilterReply = iota + 1
	// Deny represents the logging will be denied by filter.
	Deny
)

type ILogger

type ILogger interface {
	Nameable

	// SetLevel sets global level for 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 fatal level.
	Fatal() Record

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

	// Level logs with specified level.
	Level(lvl Level) Record

	// Event writes raw logging event.
	Event(e *LogEvent)
}

ILogger represents lork logging interface definition.

func Logger

func Logger(name ...string) ILogger

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

func LoggerC

func LoggerC() ILogger

LoggerC get a global lork logger with a caller package name. Note: this will call runtime.Caller function.

func NewClassicLogger

func NewClassicLogger(name string, writer *MultiWriter) ILogger

NewClassicLogger create a classic ILogger. This logger is a builtin implementation.

type ILoggerFactory added in v0.7.0

type ILoggerFactory interface {
	// Logger gets a ILogger with given name
	Logger(name string) ILogger
}

ILoggerFactory represents a factory to get loggers.

type Level

type Level int8

Level type definition for logging level.

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

func ParseLevel

func ParseLevel(lvl string) Level

ParseLevel converts a level string into lork level value.

func (Level) String

func (l Level) String() string

type Lifecycle

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

Lifecycle represents the lifecycle of component.

type LogBridgeOption added in v0.7.0

type LogBridgeOption struct {
	Name  string
	Level Level
}

type LogEvent

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

func MakeEvent

func MakeEvent(p []byte) *LogEvent

MakeEvent makes LogEvent from json string. The LevelFieldKey, TimestampFieldKey and MessageFieldKey field key must keep the same with lork.

func NewLogEvent

func NewLogEvent() *LogEvent

NewLogEvent gets a LogEvent from pool.

func (*LogEvent) Copy

func (e *LogEvent) Copy() *LogEvent

func (*LogEvent) Fields

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

Fields gets extra key and value bytes.

func (*LogEvent) Level

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

Level returns level string bytes.

func (*LogEvent) LevelInt

func (e *LogEvent) LevelInt() Level

LevelInt returns level int value.

func (*LogEvent) LoggerName added in v0.7.0

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

LoggerName return logger name bytes.

func (*LogEvent) Message

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

Message returns message bytes.

func (*LogEvent) Recycle

func (e *LogEvent) Recycle()

func (*LogEvent) Timestamp added in v0.7.0

func (e *LogEvent) Timestamp() int64

Timestamp returns unix timestamp in nano second.

type LoggerContext added in v0.7.0

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

func NewLoggerContext added in v0.7.0

func NewLoggerContext(newLogger NewLogger) *LoggerContext

NewLoggerContext creates a new instance of LoggerContext.

func (*LoggerContext) Logger added in v0.7.0

func (c *LoggerContext) Logger(name string) ILogger

Logger is implementation for ILoggerFactory.

func (*LoggerContext) RealLogger added in v0.7.0

func (c *LoggerContext) RealLogger(name string) *namedLogger

RealLogger gets a namedLogger with given name.

type ManualConfigurator added in v0.7.0

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

func Manual added in v0.7.0

func Manual() *ManualConfigurator

Manual gets ManualConfigurator to use.

func (*ManualConfigurator) AddWriter added in v0.7.0

func (c *ManualConfigurator) AddWriter(writers ...Writer)

func (*ManualConfigurator) Attached added in v0.7.0

func (c *ManualConfigurator) Attached(writer Writer) bool

func (*ManualConfigurator) Configure added in v0.7.0

func (*ManualConfigurator) GetWriter added in v0.7.0

func (c *ManualConfigurator) GetWriter(name string) Writer

func (*ManualConfigurator) ResetWriter added in v0.7.0

func (c *ManualConfigurator) ResetWriter()

type MultiWriter

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

MultiWriter represents multiple writer which implements EventWriter. This writer is used as output which will implement ILogger.

func NewMultiWriter

func NewMultiWriter() *MultiWriter

NewMultiWriter creates a new multiple writer.

func (*MultiWriter) AddWriter

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

AddWriter adds a lork writer into multi writer.

func (*MultiWriter) Attached added in v0.7.0

func (mw *MultiWriter) Attached(writer Writer) bool

func (*MultiWriter) GetWriter added in v0.7.0

func (mw *MultiWriter) GetWriter(name string) Writer

func (*MultiWriter) ResetWriter added in v0.7.0

func (mw *MultiWriter) ResetWriter()

func (*MultiWriter) Size added in v0.7.0

func (mw *MultiWriter) Size() int

func (*MultiWriter) Write

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

func (*MultiWriter) WriteEvent

func (mw *MultiWriter) WriteEvent(event *LogEvent) (err error)

type Nameable added in v0.7.0

type Nameable interface {
	// Name returns the name of this object. The name uniquely identifies the object.
	Name() string
}

Nameable a simple interface to define an object to return name.

type NewConverter

type NewConverter func() Converter

type NewLogger added in v0.7.0

type NewLogger func(name string, writer *MultiWriter) ILogger

type PatternEncoderOption

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

type Provider added in v0.7.0

type Provider interface {
	// Name the name of this provider.
	Name() string

	// Prepare prepares the provider.
	Prepare()

	// LoggerFactory gets ILoggerFactory from this provider.
	LoggerFactory() ILoggerFactory
}

Provider provides ILoggerFactory to get logger.

func NewClassicProvider added in v0.7.0

func NewClassicProvider() Provider

NewClassicProvider create s Provider for classic logger.

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

	// 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

	// Ints32 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

	// Ints64 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

	// Uints32 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

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

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

	// Msge outputs log without message
	Msge()

	// 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

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(options ...func(*TimeBasedRPOption)) RollingPolicy

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

type SizeAndTimeBasedRPOption

type SizeAndTimeBasedRPOption struct {
	FilenamePattern string
	MaxFileSize     string
	MaxHistory      int
}

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

type SocketReader

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

func NewSocketReader

func NewSocketReader(options ...func(*SocketReaderOption)) *SocketReader

NewSocketReader creates a new instance of socket reader.

func (*SocketReader) Start

func (sr *SocketReader) Start()

func (*SocketReader) Stop

func (sr *SocketReader) Stop()

type SocketReaderOption

type SocketReaderOption struct {
	Path string
	Port int
}

type SocketWriterOption

type SocketWriterOption struct {
	Name              string
	RemoteUrl         string
	QueueSize         int
	ReconnectionDelay time.Duration
	Filter            Filter
}

type SyslogWriterOption added in v0.6.1

type SyslogWriterOption struct {
	Name string
	Tag  string
	// See net.Dial
	Address, Network string
	Filter           Filter
}

type TimeBasedRPOption

type TimeBasedRPOption struct {
	FilenamePattern string
	MaxHistory      int
}

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

type Writer

type Writer interface {
	Nameable

	// DoWrite this is where a writer accomplishes its work.
	// Lork will send LogEvent to this writer.
	DoWrite(event *LogEvent) error
}

Writer is interface represents the raw writer of lork. The lork will write LogEvent without any transform.

func NewBytesWriter added in v0.7.0

func NewBytesWriter(w BytesWriter) Writer

NewBytesWriter creates a Writer with given BytesWriter. BytesWriter will write data synchronously cause the order of goroutine is messy.

func NewConsoleWriter

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

NewConsoleWriter creates a new instance of console writer.

func NewEventWriter added in v0.7.0

func NewEventWriter(w EventWriter) Writer

NewEventWriter creates a Writer with given EventWriter.

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 writer via socket.

func NewSyncWriter added in v0.7.0

func NewSyncWriter(w Writer) Writer

NewSyncWriter creates a new synchronized writer which will lock when writing LogEvent.

func NewSyslogWriter added in v0.6.1

func NewSyslogWriter(options ...func(option *SyslogWriterOption)) Writer

NewSyslogWriter create a logging writer via syslog.

type WriterAttachable added in v0.7.0

type WriterAttachable interface {
	// AddWriter add one or more writer to this bucket.
	AddWriter(writers ...Writer)

	// GetWriter gets a writer with given name.
	GetWriter(name string) Writer

	// Attached check if the given writer is attached.
	Attached(writer Writer) bool

	// ResetWriter will remove and stop all writers added before.
	ResetWriter()
}

WriterAttachable is interface definition for attaching writers to objects.

Directories

Path Synopsis
bind
logrus Module
zap Module
zero Module
bridge module
example module

Jump to

Keyboard shortcuts

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