logger

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2023 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	//EvsEmpty is an empty source to create log records with no source record
	EvsEmpty = Source{}

	//EvsDebug is a default event source to mark debug messages
	EvsDebug = Source{
		Text:  "DEBUG",
		Open:  "[",
		Close: "]",
	}

	//EvsMain represents main() function as an event source
	EvsMain = Source{
		Text:  "MAIN",
		Open:  "[",
		Close: "]",
	}
)
View Source
var AnsiEscaper = regexp.MustCompile(`\033\[\d*m`)

AnsiEscaper is a regexp to find ANSI escape characters in text

View Source
var CSVHead = "Event ID;Time;Level;Source;Text;\n"
View Source
var LogPatternCSV = "%s;%s;%s;%s;%s;\n"

LogPatternCSV is the default log pattern to transform events into csv records. Structure is: eventID;time;level;source;text

View Source
var LogPatternPureText = "%s\n"

LogPatternPureText is used to create pure text messages without time, id, etc. Only line break is added.

View Source
var SentryPattern = "[%s] %s %s %s"

SentryPattern is used to create records for Sentry

Functions

func AvoidANSI

func AvoidANSI(s string) string

AvoidANSI uses regex to drop all ANSI escape sequences in event text.

func FormatCSV

func FormatCSV(e Event, timeFormat string) string

FormatCSV returns event data in string formatted accordingly to LogPatternCSV

func FormatColors

func FormatColors(f Format, s string) string

FormatColors is a specific method to add ANSI escape sequences to log entries in CLI

func FormatJSON

func FormatJSON(e Event, timeFormat string) ([]byte, error)

Format returns event data in string formatted accordingly to LogPatternJSON

func FormatOutput

func FormatOutput(e Event, timeFormat string) string

FormatOutput returns event data in string formatted accordingly to LogPattern

func FormatOutputPureText

func FormatOutputPureText(e Event) string

func FormatOutputSentry

func FormatOutputSentry(e Event, appID string) string

FormatOutputSentry returns event data in string formatted accordingly to SentryPattern

Types

type CLI

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

CLI is a default logger that formats event data and pushes to default output via fmt.Print

func NewCLI

func NewCLI(pureText bool, lTypes ...LogType) *CLI

NewCLI returns instance of CLI logger with desired log types support

func (*CLI) Log

func (l *CLI) Log(e Event, timeFormat string) error

Log pushes event data into default output

func (*CLI) Type

func (l *CLI) Type() []LogType

Type returns set of types supported by the logger

type CSVFileLogger

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

func NewCSVtext

func NewCSVtext(path string, truncate bool, rotateFiles int, f IFile, lTypes ...LogType) (*CSVFileLogger, error)

NewCSVtext returns logger capable of creating csv file records.

By passing IFile interface as f you can set the initial object to write logs to. Otherwise path & truncate will be used to create new file. Note: if rotateFiles > 0, file will be changed after this period of time any way

func (*CSVFileLogger) LastLog

func (l *CSVFileLogger) LastLog() time.Time

LastLog returns last time the logger was used

func (*CSVFileLogger) Log

func (l *CSVFileLogger) Log(e Event, timeFormat string) error

Log pushes event data into default output

func (*CSVFileLogger) SetLastLog

func (l *CSVFileLogger) SetLastLog(t time.Time)

SetLastLog sets last time the logger was used

func (*CSVFileLogger) Type

func (l *CSVFileLogger) Type() []LogType

Type returns set of types supported by the logger

type EvDefault

type EvDefault struct {
	Source    Source
	Type      LogType
	Format    Format
	TimeFixed bool
}

EvDefault is a helper that can be used to create events with pre-defined properties. It will create events with defined Source, Type & Format in case these props are set to non-default.

Several EvDefaults can be created in main() to cover whole app needs or one by one in methods where similar events are used.

func (EvDefault) Critical

func (ed EvDefault) Critical(t string) Event

Critical returns event with CRIT level and type, source, format set to ed parameters

func (EvDefault) Empty

func (ed EvDefault) Empty() Event

Empty returns event with INFO level, no text and default type, source and format

func (EvDefault) Error

func (ed EvDefault) Error(t string) Event

Error returns event with ERR level and type, source, format set to ed parameters

func (EvDefault) Fatal

func (ed EvDefault) Fatal(t string) Event

Fatal returns event with FATAL level and type, source, format set to ed parameters

func (EvDefault) Info

func (ed EvDefault) Info(t string) Event

Info returns event with INFO level and type, source, format set to ed parameters

func (EvDefault) Note

func (ed EvDefault) Note(t string) Event

Note returns event with NOTE level and type, source, format set to ed parameters

func (EvDefault) Panic

func (ed EvDefault) Panic(t string) Event

Panic returns event with PANIC level and type, source, format set to ed parameters

func (EvDefault) Warning

func (ed EvDefault) Warning(t string) Event

Warning returns event with WARN level and type, source, format set to ed parameters

type Event

type Event struct {
	ID     string
	Level  Level
	Type   LogType
	Source Source
	Time   time.Time
	Text   string
	Format Format

	//TimeFixed should be set to true if the app must log same event instance without updating
	//event's Time value. E.g. for making several records with different text, but for same time.
	TimeFixed bool
}

Event represents any event that can occur during runtime. All Event fields are public and it's perfectly safe to modify Event without using API.

Event can be reused after being logged: new calling to Log() will log the event with new ID.

func Critical

func Critical(t string) Event

Critical returns event with CRIT level and default type, source and format

func Empty

func Empty() Event

Empty returns event with INFO level, no text and default type, source and format

func Error

func Error(t string) Event

Error returns event with ERR level and default type, source and format

func Fatal

func Fatal(t string) Event

Fatal returns event with FATAL level and default type, source and format

func Info

func Info(t string) Event

Info returns event with INFO level and default type, source and format

func Note

func Note(t string) Event

Note returns event with NOTE level and default type, source and format

func Panic

func Panic(t string) Event

Panic returns event with PANIC level and default type, source and format

func Warning

func Warning(t string) Event

Warning returns event with WARN level and default type, source and format

func (Event) Any

func (e Event) Any() Event

Any sets event Type to Any

func (Event) BgBlack

func (e Event) BgBlack() Event

BgBlack sets event Format to BgBlack

func (Event) BgBlue

func (e Event) BgBlue() Event

BgBlue sets event Format to BgBlue

func (Event) BgCyan

func (e Event) BgCyan() Event

BgCyan sets event Format to BgCyan

func (Event) BgGreen

func (e Event) BgGreen() Event

BgGreen sets event Format to BgGreen

func (Event) BgMagenta

func (e Event) BgMagenta() Event

BgMagenta sets event Format to BgMagenta

func (Event) BgRed

func (e Event) BgRed() Event

BgRed sets event Format to BgRed

func (Event) BgWhite

func (e Event) BgWhite() Event

BgWhite sets event Format to BgWhite

func (Event) BgYellow

func (e Event) BgYellow() Event

BgYellow sets event Format to BgYellow

func (Event) Blue

func (e Event) Blue() Event

Blue sets event Format to Blue

func (Event) Critical

func (e Event) Critical() Event

Critical sets event Level to CRIT

func (Event) Cyan

func (e Event) Cyan() Event

Cyan sets event Format to Cyan

func (Event) Debug

func (e Event) Debug() Event

Debug sets event Type to Debug

func (Event) Error

func (e Event) Error() Event

Error sets event Level to ERR

func (Event) Fatal

func (e Event) Fatal() Event

Fatal sets event Level to FATAL

func (Event) FixTime

func (e Event) FixTime() Event

FixTime marks event time as fixed, so logger will NOT use time.Now() value each time event is logged

func (Event) FlushID

func (e Event) FlushID() Event

FlushID cleans event ID

func (Event) Gray

func (e Event) Gray() Event

Gray sets event Format to Gray

func (Event) Green

func (e Event) Green() Event

Green sets event Format to Green

func (Event) Info

func (e Event) Info() Event

Info sets event Level to INFO

func (Event) Magenta

func (e Event) Magenta() Event

Magenta sets event Format to Magenta

func (Event) Main

func (e Event) Main() Event

Main sets event Type to Main

func (Event) None

func (e Event) None() Event

None sets event Format to None

func (Event) Note

func (e Event) Note() Event

Note sets event Level to NOTE

func (Event) Panic

func (e Event) Panic() Event

Panic sets event Level to PANIC

func (Event) Red

func (e Event) Red() Event

Red sets event Format to Red

func (Event) SetID

func (e Event) SetID(id string) Event

SetID sets event ID. It will be used by LogProcessor

func (Event) SetText

func (e Event) SetText(t string) Event

func (Event) Src

func (e Event) Src(s Source) Event

Src returns event with source = s

func (Event) UnFixTime

func (e Event) UnFixTime() Event

UnFixTime marks event time as non-fixed, so logger WILL use time.Now() value each time event is logged

func (Event) Verbose

func (e Event) Verbose() Event

Verbose sets event Type to Verbose

func (Event) Warning

func (e Event) Warning() Event

Warning sets event Level to WARN

func (Event) White

func (e Event) White() Event

White sets event Format to White

func (Event) Yellow

func (e Event) Yellow() Event

Yellow sets event Format to Yellow

type Force

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

type Format

type Format int

Format represents any possible format to output log strings. Default formats are for colored CLI output, but logger developers can create new formats to suit specific logger options.

const (
	// None should represent default log format for the logger
	None Format = iota

	Red
	Green
	Yellow
	Blue
	Magenta
	Cyan
	Gray
	White
	BgBlack
	BgRed
	BgGreen
	BgYellow
	BgBlue
	BgMagenta
	BgCyan
	BgWhite
)

type IFile

type IFile interface {
	Write(b []byte) (n int, err error)
	WriteString(s string) (n int, err error)
	Close() error
}

IFile represents file in the filesystem that's used to log events

type ILogger

type ILogger interface {
	//Log processes event and logs according to logger's internal rules
	Log(e Event, timeFormat string) error

	//Type returns whole list of types a logger should receive.
	//Normally you don't need to check event type in the logger as the log processor will not
	//send events that have wrong LogType
	Type() []LogType
}

ILogger represents general logger interface that can process specific event types and log events into abstract log. It can be CLI, text, SQL, Redis, Sentry, etc.

type JSONFileLogger

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

func NewJSONtext

func NewJSONtext(path string, truncate bool, rotateFiles int, f IFile, lTypes ...LogType) (*JSONFileLogger, error)

NewJSONtext returns logger capable of creating json-encoded records in text file.

Note: current realization fills file with json-objects, but does not create array of records ([...]). It makes log writing faster, but the only way to read valid JSON from the file is to frame its contents by [] before parsing..

By passing IFile interface as f you can set the initial object to write logs to. Otherwise path & truncate will be used to create new file. Note: if rotateFiles > 0, file will be changed after this period of time any way

func (*JSONFileLogger) LastLog

func (l *JSONFileLogger) LastLog() time.Time

LastLog returns last time the logger was used

func (*JSONFileLogger) Log

func (l *JSONFileLogger) Log(e Event, timeFormat string) error

Log pushes event data into default output

func (*JSONFileLogger) SetLastLog

func (l *JSONFileLogger) SetLastLog(t time.Time)

SetLastLog sets last time the logger was used

func (*JSONFileLogger) Type

func (l *JSONFileLogger) Type() []LogType

Type returns set of types supported by the logger

type Level

type Level int

Level determines how critical the event is

const (

	//INFO informs reader about any event in app
	INFO Level

	//NOTE is like info, but with higher priority (e.g. for reader to make notes)
	NOTE

	//WARN warns about potentially dangreous situation
	WARN

	//ERR reports that something bad has happened
	ERR

	//CRIT reports that something REALLY bad has happened
	CRIT

	//Panic makes app panic after event is logged
	PANIC

	//FATAL makes app exit after event is logged
	FATAL
)

func (Level) IsError

func (l Level) IsError() bool

IsError returns true in case level of event is high enough to be a problem right now.

func (Level) String

func (l Level) String() string

type LogPatternJSON

type LogPatternJSON struct {
	ID     string `json:"id"`
	Time   string `json:"time"`
	Level  string `json:"level"`
	Source string `json:"source"`
	Text   string `json:"text"`
}

type LogProcessor

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

LogProcessor manages all available loggers, processes log errors and sends events to external routine if needed

func New

func New(useID bool, timeFormat string, errChan chan (error), reportErrors bool, la ...ILogger) *LogProcessor

New creates new LogProcessor with selected parameters.

If timeFormat is an empty string, time.UnixDate will be used. If useID is false, events will have e,pty ID

func (*LogProcessor) AddLoggers

func (lp *LogProcessor) AddLoggers(la ...ILogger)

AddLoggers adds list of loggers to EP's pool

func (*LogProcessor) FatalInCaseErr

func (lp *LogProcessor) FatalInCaseErr(err interface{}, lt ...LogType)

FatalInCaseErr does nothing if nil or event with level<ERR is provided, but calls os.Exit() in case error is not nil.

May generate doubles in case same logger is used for several types presenting in lt. Doubles will have same ID

func (*LogProcessor) ForceLevel

func (ep *LogProcessor) ForceLevel(l Level)

ForceLevel makes EP forsibly change leve of every event to l

func (*LogProcessor) ForceSource

func (ep *LogProcessor) ForceSource(s Source)

ForceSource makes EP forsibly change source of every event to s

func (*LogProcessor) Log

func (lp *LogProcessor) Log(e Event)

Log logs event according to it's type and level.

It panics after logging PANIC-level and calls to exit(2) after logging FATAL event.

func (*LogProcessor) LogErrOnly

func (lp *LogProcessor) LogErrOnly(err interface{}, lt ...LogType)

LogErrOnly simply logs any error or does nothing in case nil.

May generate doubles in case same logger is used for several types presenting in lt. Doubles will have same ID

func (LogProcessor) LogRed

func (lp LogProcessor) LogRed(e Event)

func (*LogProcessor) PanicInCaseErr

func (lp *LogProcessor) PanicInCaseErr(err interface{}, lt ...LogType)

PanicInCaseErr does nothing if nil or event with level<ERR is provided, but panics in case error is not nil.

May generate doubles in case same logger is used for several types presenting in lt. Doubles will have same ID

func (*LogProcessor) SendEventToChan

func (lp *LogProcessor) SendEventToChan(e Event)

func (*LogProcessor) SetErrChan

func (ep *LogProcessor) SetErrChan(evChan chan (Event))

SetErrChan sets new error channel to send log process errors.

func (*LogProcessor) UnSetErrChan

func (ep *LogProcessor) UnSetErrChan()

UnSetErrChan prevents EP from sending log errors to outer routine and closes the error channel

type LogType

type LogType int

LogType represents type of logger that should log the event. It can be used in cases when some events have specific meaning and should not appear in some logs. E.g. debug messages in CLI or request logs

const (
	//Any-logtyped event will be logged by all available loggers
	Any LogType = iota

	//Main represents main event sequence that stores all app events
	Main

	//ErrorFlow represents error log in case errors should not be
	//in main event sequence
	ErrorFlow

	//Verbose indicates that this specific event should be considered as verbose
	//and app may want to use specific logger to treat that event.
	Verbose

	//Debug event typically means info that should be read by developer or QA only
	Debug
)

type MockFile

type MockFile struct {
	Text []string
}

func (*MockFile) Close

func (l *MockFile) Close() error

func (*MockFile) Write

func (l *MockFile) Write(b []byte) (n int, err error)

func (*MockFile) WriteString

func (l *MockFile) WriteString(s string) (n int, err error)

type MockLogger

type MockLogger struct {
	LoggedData Event
	Format     string
	LogType    []LogType
	// contains filtered or unexported fields
}

func (*MockLogger) Log

func (l *MockLogger) Log(e Event, timeFormat string) error

func (*MockLogger) Type

func (l *MockLogger) Type() []LogType

type PlaintextFileLogger

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

func NewPlaintext

func NewPlaintext(path string, pureText bool, truncate bool, rotateFiles int, f IFile, lTypes ...LogType) (*PlaintextFileLogger, error)

NewPlaintext returns logger capable of appending strings to text file.

By passing IFile interface as f you can set the initial object to write logs to. Otherwise path & truncate will be used to create new file. Note: if rotateFiles > 0, file will be changed after this period of time any way

func (*PlaintextFileLogger) LastLog

func (l *PlaintextFileLogger) LastLog() time.Time

LastLog returns last time the logger was used

func (*PlaintextFileLogger) Log

func (l *PlaintextFileLogger) Log(e Event, timeFormat string) error

Log pushes event data into default output

func (*PlaintextFileLogger) SetLastLog

func (l *PlaintextFileLogger) SetLastLog(t time.Time)

SetLastLog sets last time the logger was used

func (*PlaintextFileLogger) Type

func (l *PlaintextFileLogger) Type() []LogType

Type returns set of types supported by the logger

type SentryLogger

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

SentryLogger uses Go-native Sentry package to log event. If you need to adjust parameters, use functions defined by github.com/getsentry/sentry-go (ConfigureScope, for example) after logger.NewSentry has been called.

func NewSentry

func NewSentry(dsn, env, rel, appID string, debug bool, tsr float64, lTypes ...LogType) (*SentryLogger, error)

NewSentry returns SentryLogger and configures Go-native Sentry package to use specified parameters

func (*SentryLogger) Log

func (l *SentryLogger) Log(e Event, timeFormat string) error

func (*SentryLogger) Type

func (l *SentryLogger) Type() []LogType

Type returns set of types supported by the logger

type Source

type Source struct {
	Text  string
	Open  string
	Close string
}

Source is just a text representation of any possible event source in the app. Its desirable to create your own sources to determine runtime problems specific to your app.

func (Source) String

func (s Source) String() string

Jump to

Keyboard shortcuts

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