slf

package module
v0.0.0-...-79153e9 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2017 License: MIT Imports: 3 Imported by: 4

README

Simple static logging facility for Golang

Build Status Go Report Card GoDoc

Brief

SLF provides easy and convenient way to organize logging and metrics reporting inside your application.

import (
    "github.com/mono83/slf/wd"
)

// Create logger with marker example
log := wd.NewLogger("example")
log.Info("Processing some staff")

Allowed logging levels are: Trace, Debug, Info, Warning, Error, Alert

Got logs but no output? Assign receivers!

By default, SLF will ignore any received. To manage output or forwarding to external logging facilities just add a receiver. Most common is stdout receiver, which can be assigned right in your func main()


import (
    "github.com/mono83/slf/wd"
    "github.com/mono83/slf/recievers/writer"
)

func main() {
        // Add ANSI standard output receiver 
        wd.AddReceiver(writer.Options{NoColor: false})
}

To remove debug and trace information, filtering may be applied

wd.AddReceiver(slf.Filter(
                ansi.New(true /*colors*/, true /*show marker*/, false /*async*/),
                writer.Options{NoColor: false},
))

More concision with placeholders

SLF supports additional parameters, that can be applied to log. These parameters can be used as placeholders values and some receiver can contain additional logic for it (for example, Logstash receiver can send placeholder values as separated columns):

log.Info("Processing user :id", params.Int{Key: "id", Value: 300})

Raw params aren't most convenient things in the world, so wd. package contains some builders for frequent params:

Func Args Description
wd.IntParam string, int
wd.Int64Param string, int
wd.CountParam int Builds integer param with key count
wd.ID64Param int Builds 64-bit integer param with key id
wd.FloatParam string, float64
wd.ErrParam error Builds param containing Go errors with key err
wd.StringParam string, string
wd.NameParam string, strings Builds string param with key name
wd.DeltaParam time.Duration Builds duration param with key delta

spf13/cobra integration

There is wrapper for spf13/cobra. Just invoke slfcobra.Wrap over your main command and CLI arguments and logging will be added:

import (
        "github.com/mono83/slf/util/slfcobra"
)

var BookCmd = slfcobra.Wrap(&cobra.Command{...})

Documentation

Index

Constants

View Source
const (
	TypeTrace     byte = 1
	TypeDebug     byte = 2
	TypeInfo      byte = 3
	TypeWarning   byte = 4
	TypeError     byte = 5
	TypeAlert     byte = 6
	TypeEmergency byte = 7

	TypeInc      byte = 100
	TypeGauge    byte = 101
	TypeDuration byte = 102
)

List of

Variables

View Source
var Nil = nilstruct{}

Nil contains No-Op logger, receiver and stats reporter

View Source
var PlaceholdersRegex = regexp.MustCompile(":[0-9a-zA-Z\\-_]+")

PlaceholdersRegex contains rules to find placeholders inside string

Functions

func ParseType

func ParseType(s string) (byte, bool)

ParseType parses incoming string type representation into byte

func ReplacePlaceholders

func ReplacePlaceholders(source string, params []Param, useBrackets bool) string

ReplacePlaceholders func replaces placeholders inside source string using provided params

Types

type Dispatcher

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

Dispatcher is wrapper over slice of receivers

func (*Dispatcher) AddMutator

func (d *Dispatcher) AddMutator(m Mutator)

AddMutator registers new mutators

func (*Dispatcher) AddReceiver

func (d *Dispatcher) AddReceiver(r Receiver)

AddReceiver registers new receiver

func (*Dispatcher) Receive

func (d *Dispatcher) Receive(e Event)

Receive handles incoming event

type Event

type Event struct {
	Time   time.Time // Event time
	Marker string    // Event owner

	Type    byte    // Event type
	Content string  // Content - either message or metrics name
	Params  []Param // Params slice
	I64     int64   // Increment or duration or gauge value
}

Event represents event information

func (Event) IsLog

func (e Event) IsLog() bool

IsLog returns true if event is logging event

func (Event) IsMetrics

func (e Event) IsMetrics() bool

IsMetrics return true if event is metrics event

func (Event) StringType

func (e Event) StringType() string

StringType returns string representation of log event type Will return empty string on metrics or invalid type

type Logger

type Logger interface {
	Trace(message string, p ...Param)
	Debug(message string, p ...Param)
	Info(message string, p ...Param)
	Warning(message string, p ...Param)
	Error(message string, p ...Param)
	Alert(message string, p ...Param)
	Emergency(message string, p ...Param)
}

Logger interface describes logger structure

type Mutator

type Mutator interface {
	Modify(*Event)
}

Mutator interface describes components, that modifies events

func FuncMutator

func FuncMutator(f func(*Event)) Mutator

FuncMutator returns Mutator built over func

type Param

type Param interface {
	// GetKey returns param key name
	GetKey() string
	// GetRaw returns raw value
	GetRaw() interface{}
	// String returns string representation of param value
	String() string
}

Param represents parameter, sent to logger or metrics

type ParamsFilter

type ParamsFilter func([]Param) []Param

ParamsFilter describes function, used to filter params list

func NewBlackListParamsFilter

func NewBlackListParamsFilter(allowedNames []string) ParamsFilter

NewBlackListParamsFilter returns params filter, that clears params with name, passed to this function

func NewWhiteListParamsFilter

func NewWhiteListParamsFilter(allowedNames []string) ParamsFilter

NewWhiteListParamsFilter return params filter, that allows only params with names, passed to this function

type Receiver

type Receiver interface {
	Receive(e Event)
}

Receiver interface represents SLF event receiver

func Filter

func Filter(r Receiver, predicate func(e Event) bool) Receiver

Filter builds new filter wrapper over receiver

type StatsReporter

type StatsReporter interface {
	// IncCounter increments a statsd-like counter with optional params
	IncCounter(name string, value int64, p ...Param)

	// UpdateGauge a statsd-like gauge ("set" of the value) with optional tags
	UpdateGauge(name string, value int64, p ...Param)

	// RecordTimer records a statsd-like timer with optional tags
	RecordTimer(name string, d time.Duration, p ...Param)

	// Timer builds returns timer, bound to this StatsReporter
	Timer(name string, p ...Param) Timer
}

StatsReporter describes common metrics reporter

type Timer

type Timer interface {
	// Done stops timer and returns elapsed time
	// If timer was already stopped, just returns elapsed time
	Done() time.Duration

	// Params returns current timer value as param
	Param(string) Param
}

Timer is interface to metrics timer

func NewTimer

func NewTimer(name string, p []Param, target StatsReporter) Timer

NewTimer builds new Timer

Directories

Path Synopsis
util

Jump to

Keyboard shortcuts

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