logger

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2021 License: MIT Imports: 7 Imported by: 1

README

go-log

Docs live at mathbalduino.com.br/go-log


Matheus Leonel Balduino

Everywhere, under @mathbalduino

Documentation

Index

Constants

View Source
const (
	// LvlTrace is a flag that if used will enable
	// Trace logs (via Logger Trace method)
	LvlTrace uint64 = 1 << iota

	// LvlDebug is a flag that if used will enable
	// Debug logs (via Logger Debug method)
	LvlDebug

	// LvlInfo is a flag that if used will enable
	// Info logs (via Logger Info method)
	LvlInfo

	// LvlWarn is a flag that if used will enable
	// Warn logs (via Logger Warn method)
	LvlWarn

	// LvlError is a flag that if used will enable
	// Error logs (via Logger Error method)
	LvlError

	// LvlFatal is a flag that if used will enable
	// Fatal logs (via Logger Fatal method)
	LvlFatal
)
View Source
const (
	// LvlProduction will enable Info, Warn, Error and Fatal logs
	LvlProduction = LvlInfo | LvlWarn | LvlError | LvlFatal

	// LvlDefaults will enable Debug and all LvlProduction logs
	LvlDefaults = LvlDebug | LvlProduction

	// LvlAll will enable all logs
	LvlAll = LvlTrace | LvlDefaults
)
View Source
const DefaultErrorKey = "error"

DefaultErrorKey is the value of the key used to store the errors returned by the DefaultErrorParser

Variables

View Source
var ErrLvlMsgSameKey = fmt.Errorf("the 'level' and 'message' keys cannot be equal")

ErrLvlMsgSameKey is an error token used to represent the situation where the given Configuration struct contains the 'LvlFieldName' and 'MsgFieldName' fields with the same value

View Source
var ErrNilChan = fmt.Errorf("the 'channel' argument cannot be nil")

ErrNilChan is threw by AsyncHandleLog when it receives a nil channel via the function argument

View Source
var ErrNilCtx = fmt.Errorf("the 'context.Context' argument cannot be nil")

ErrNilCtx is threw by AsyncHandleLog when it receives a nil context via the function argument

View Source
var ErrNilErrorParser = fmt.Errorf("the 'ErrorParser' cannot be nil")

ErrNilErrorParser is an error token used to represent that the given ErrorParser is nil and if it's accepted, a nil pointer can happen

View Source
var ErrNilWaitGroup = fmt.Errorf("the 'WaitGroup' argument cannot be nil")

ErrNilWaitGroup is threw by AsyncHandleLog when it receives a nil WaitGroup via the function argument

Functions

func AsyncHandleLog

func AsyncHandleLog(ctx context.Context, c <-chan Log, wg WaitGroup) error

AsyncHandleLog will wait on the given send-only channel, and forwarding any received Log to the internal "handleLog" function.

Note that this function must be used to implement custom async strategies, since it's the only way to access the internal "handleLog" function

func BoldRedString

func BoldRedString(msg string) string

BoldRedString will wrap the given string between the bold red and reset ANSI codes.

Terminals with ANSI code support will print the string to the screen using bold red as the font color

func ColorizeStrByLvl

func ColorizeStrByLvl(lvl uint64, msg string) string

ColorizeStrByLvl will colorize the log msg using the ANSI color code associated with the log level

func CyanString

func CyanString(msg string) string

CyanString will wrap the given string between the cyan and reset ANSI codes.

Terminals with ANSI code support will print the string to the screen using cyan as the font color

func DarkGreyString

func DarkGreyString(msg string) string

DarkGreyString will wrap the given string between the dark grey and reset ANSI codes.

Terminals with ANSI code support will print the string to the screen using dark grey as the font color

func Debug

func Debug(msg string, adHocFields ...LogFields)

Debug will create a new default log with the Debug level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func Error

func Error(msg string, adHocFields ...LogFields)

Error will create a new default log with the Error level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func ErrorFrom

func ErrorFrom(e error, adHocFields ...LogFields)

ErrorFrom will create a new default log with the Error level, using the given error and adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

Note that this method will call the default 'ErrorParser' function to extract the log message and custom fields from the given error. These custom fields will be overridden by the 'adHocFields' param

func Fatal

func Fatal(msg string, adHocFields ...LogFields)

Fatal will create a new default log with the Fatal level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func FatalFrom

func FatalFrom(e error, adHocFields ...LogFields)

FatalFrom will create a new default log with the Fatal level, using the given error and adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

Note that this method will call the default 'ErrorParser' function to extract the log message and custom fields from the given error. These custom fields will be overridden by the 'adHocFields' param

func Info

func Info(msg string, adHocFields ...LogFields)

Info will create a new default log with the Info level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func LightGreyString

func LightGreyString(msg string) string

LightGreyString will wrap the given string between the light grey and reset ANSI codes.

Terminals with ANSI code support will print the string to the screen using light grey as the font color

func LvlToString

func LvlToString(lvl uint64) string

LvlToString will take the given log level and return the string that represents it

Note that this function can only translate default log levels

func OutputAnsiToStdout

func OutputAnsiToStdout(lvl uint64, msg string, _ LogFields)

OutputAnsiToStdout will take some log and write it to the os.Stdout, using ANSI codes to colorize it accordingly to the log level

func OutputPanicOnFatal

func OutputPanicOnFatal(lvl uint64, msg string, fields LogFields)

OutputPanicOnFatal will call "panic" if the lvl of the given log is "LvlFatal", using the "error" interface inside the fields as argument, if present. Otherwise, the log msg string will be used to create a new error (using fmt.Errorf)

func RedString

func RedString(msg string) string

RedString will wrap the given string between the red and reset ANSI codes.

Terminals with ANSI code support will print the string to the screen using red as the font color

func Trace

func Trace(msg string, adHocFields ...LogFields)

Trace will create a new default log with the Trace level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func Warn

func Warn(msg string, adHocFields ...LogFields)

Warn will create a new default log with the Warn level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func YellowString

func YellowString(msg string) string

YellowString will wrap the given string between the yellow and reset ANSI codes.

Terminals with ANSI code support will print the string to the screen using yellow as the font color

Types

type AsyncScheduler

type AsyncScheduler interface {
	// NextChannel must return a valid, non-nil,
	// receive-only channel
	NextChannel() chan<- Log

	// Shutdown must send a signal (and wait response)
	// to the running go routines, exiting them
	Shutdown()
}

AsyncScheduler is used as a source of channels that are used to send new Logs to worker goroutines, handling Logs in an asynchronous way

func DefaultAsyncScheduler

func DefaultAsyncScheduler(nGoRoutines uint64, chanCap uint64) AsyncScheduler

DefaultAsyncScheduler will create one channel by goroutine, with the given capacity, and setup a goroutine that will handle newly created Logs.

Note that if nGoRoutines is zero, nothing happens and the returned AsyncScheduler will be nil

type Configuration

type Configuration struct {
	// AsyncScheduler will be used to distinguish
	// between a sync (if nil) or async (if not nil)
	// approach
	AsyncScheduler AsyncScheduler

	// LvlFieldName is used to customize the name of
	// the key that represents the level of the Log
	//
	// Note that it cannot be equal to the MsgFieldName
	LvlFieldName string

	// MsgFieldName is used to customize the name of
	// the key that represents the message of the Log
	//
	// Note that it cannot be equal to the LvlFieldName
	MsgFieldName string

	// LvlsEnabled is an integer that represents which
	// Log levels are enabled.
	//
	// Note that it is intended to be used as a combination
	// ("or" bitwise operation) of log levels
	LvlsEnabled uint64

	// ErrorParser is a function that takes an error and
	// return a msg string and an optional collection of fields
	// (used by ErrorFrom and FatalFrom methods)
	ErrorParser func(error) (string, LogFields)
}

Configuration is a struct that holds global src configurations

func DefaultConfig

func DefaultConfig() Configuration

DefaultConfig creates a default Logger configuration, with a synchronous approach (nil AsyncScheduler), omitting only Trace logs, using "lvl" and "msg" as LvlFieldName and MsgFieldName, respectively, and extracting only the error message via 'ErrorParser'

type Hooks

type Hooks = map[string]func(Log) interface{}

Hooks is just an alias to a map that contains information about fields keys/value (via function call)

type Log

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

Log is a struct that represents a newly created log

It is intended to be internal only, exported just to allow outside type reference

func (Log) Field

func (l Log) Field(key string) interface{}

Field will return the value associated with the given key

Note that if this method is called in pre hooks, the adHoc and post fields aren't ready yet, so the returned value may be overridden by them. If called in post hook N, it can only see the result of the application of the N-1 previous post hooks. The returned value can be overridden by the N+1 next post hooks

Pay attention

type LogFields

type LogFields = map[string]interface{}

LogFields is just an alias to a map that represents the fields of the log

func DefaultErrorParser

func DefaultErrorParser(err error) (string, LogFields)

DefaultErrorParser will return a tuple containing the error string and the following map: { "error": err }

type Logger

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

Logger is a struct that represents a base log template, that contains basic information on how to handle new logs

func New

func New(config Configuration) *Logger

New creates a new Logger instance, validating the given configuration

Note that if the given configuration is invalid, panic will be called with the proper errors

func NewDefault

func NewDefault() *Logger

NewDefault will create a basic sync Logger instance that outputs newly created logs to the terminal (using ANSI codes), using 'lvl' and 'msg' as level and message keys and enabling only the default log levels

func (*Logger) Configuration

func (l *Logger) Configuration(c Configuration)

func (*Logger) Debug

func (l *Logger) Debug(msg string, adHocFields ...LogFields)

Debug will create a new log with the Debug level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func (*Logger) Error

func (l *Logger) Error(msg string, adHocFields ...LogFields)

Error will create a new log with the Error level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func (*Logger) ErrorFrom

func (l *Logger) ErrorFrom(e error, adHocFields ...LogFields)

ErrorFrom will create a new log with the Error level, using the given error and adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

Note that this method will call the 'ErrorParser' configured function to extract the log message and custom fields from the given error. These custom fields will be overridden by the 'adHocFields' param

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, adHocFields ...LogFields)

Fatal will create a new log with the Fatal level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func (*Logger) FatalFrom

func (l *Logger) FatalFrom(e error, adHocFields ...LogFields)

FatalFrom will create a new log with the Fatal level, using the given error and adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

Note that this method will call the 'ErrorParser' configured function to extract the log message and custom fields from the given error. These custom fields will be overridden by the 'adHocFields' param

func (*Logger) Field

func (l *Logger) Field(key string) interface{}

Field act as a getter for src fields

Note that this method will ignore pre/post fields

func (*Logger) Fields

func (l *Logger) Fields(fields LogFields) *Logger

Fields will append the given LogFields to the Logger fields, overriding any already existing fields and returning a new Logger instance

func (*Logger) Info

func (l *Logger) Info(msg string, adHocFields ...LogFields)

Info will create a new log with the Info level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func (*Logger) Log

func (l *Logger) Log(lvl uint64, msg string, adHocFields []LogFields)

Log is the base method that creates a new log, being used by all other log methods (Trace, Debug, Warn, ...). If there's the need to create custom log levels, use this method.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func (*Logger) Outputs

func (l *Logger) Outputs(output Output, outputs ...Output) *Logger

Outputs will append the given output params (including the variadic ones) to the Logger outputs and return a new Logger instance

func (*Logger) PostHooks

func (l *Logger) PostHooks(hooks Hooks) *Logger

PostHooks will append the given Hooks to the Logger post Hooks, overriding any already existing hooks and returning a new Logger instance

func (*Logger) PreHooks

func (l *Logger) PreHooks(hooks Hooks) *Logger

PreHooks will append the given Hooks to the Logger pre Hooks, overriding any already existing hooks and returning a new Logger instance

func (*Logger) RawFields

func (l *Logger) RawFields(fields LogFields) *Logger

RawFields will set the given LogFields directly to the Logger fields, discarding the previous value and returning a new Logger instance

func (*Logger) RawOutputs

func (l *Logger) RawOutputs(output Output, outputs ...Output) *Logger

RawOutputs will set the given output params (including the variadic ones) to the Logger outputs, discarding the old value and returning a new Logger instance

func (*Logger) RawPostHooks

func (l *Logger) RawPostHooks(hooks Hooks) *Logger

RawPostHooks will set the given Hooks to the Logger post Hooks, discarding the previous value and returning a new Logger instance

func (*Logger) RawPreHooks

func (l *Logger) RawPreHooks(hooks Hooks) *Logger

RawPreHooks will set the given Hooks to the Logger pre Hooks, discarding the previous value and returning a new Logger instance

func (*Logger) Trace

func (l *Logger) Trace(msg string, adHocFields ...LogFields)

Trace will create a new log with the Trace level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

func (*Logger) Warn

func (l *Logger) Warn(msg string, adHocFields ...LogFields)

Warn will create a new log with the Warn level, using the given adHocFields, if enabled.

Note that the 'adHocFields' param is variadic just to simulate optional params. Latter values will override former ones

type Output

type Output = func(lvl uint64, msg string, fields LogFields)

Output is just an alias to a function that is intended to handle newly created logs and persist/print it to somewhere

func OutputJsonToWriter

func OutputJsonToWriter(w io.Writer, onError func(error)) Output

OutputJsonToWriter will parse the log fields to JSON and write it to the given Writer interface, calling onError with any errors that occur between the Marshal()/Write() call

func OutputToWriter

func OutputToWriter(w io.Writer, parser OutputParser, onError func(error)) Output

OutputToWriter will call the given parser and write the results to the given io.Writer, calling 'onError' with any errors that occur

type OutputParser

type OutputParser = func(LogFields) ([]byte, error)

OutputParser is just an alias to a function that is used to parse the LogFields into a byte array, in order to write it to a file, etc...

type WaitGroup

type WaitGroup interface {
	Wait()
	Done()
	Add(int)
}

WaitGroup is an interface used just to ease tests.

Directories

Path Synopsis
beautify command

Jump to

Keyboard shortcuts

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