logger

package module
v2.2.6 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: GPL-3.0 Imports: 14 Imported by: 3

README

Logger

Logger adds the option to write colored output

Documentation

Index

Constants

View Source
const (
	DEFAULT_COLOR        = "\x1b[0m"
	BLACK_COLOR          = "\x1b[30m"
	DARK_RED_COLOR       = "\x1b[31m"
	DARK_GREEN_COLOR     = "\x1b[32m"
	DARK_YELLOW_COLOR    = "\x1b[33m"
	DARK_BLUE_COLOR      = "\x1b[34m"
	DARK_MAGENTA_COLOR   = "\x1b[35m"
	DARK_CYAN_COLOR      = "\x1b[36m"
	DARK_WHITE_COLOR     = "\x1b[37m"
	BRIGHT_BLACK_COLOR   = "\x1b[90m"
	BRIGHT_RED_COLOR     = "\x1b[31m"
	BRIGHT_GREEN_COLOR   = "\x1b[32m"
	BRIGHT_YELLOW_COLOR  = "\x1b[33m"
	BRIGHT_BLUE_COLOR    = "\x1b[34m"
	BRIGHT_MAGENTA_COLOR = "\x1b[35m"
	BRIGHT_CYAN_COLOR    = "\x1b[36m"
	WHITE_COLOR          = "\x1b[37m"
)

This colors can be used to customize the output. You can achieve this by simply doing:

fmt.Printf("%s%s%s", logger.DARK_RED_COLOR, "My string", "logger.DEFAULT_COLOR")

Remember to always use the DEFAULT_COLOR to reset the terminal to the default color. You can check if the output is a terminal window or not with the ToTerminal function.

Variables

View Source
var (
	// LogFileTimeFormat is the format that is used to create
	// the log files for the HugeLogger. It must not be changed
	// after the creation of the first HugeLogger, otherwise logs
	// with the old format will be lost
	LogFileTimeFormat = "06.01.02-15.04.05"
	// LogChunkSize determines both the numbers of logs kept in memory
	// and the number of logs saved in each file. It must not be changed
	// after the creation of the first HugeLogger
	LogChunkSize = 1000
	// LogFileExtension can be used to change the file extenstion of the
	// log files
	LogFileExtension = "data"

	MaxLogsPerScan           = 200
	ScanInterval             = 200 * time.Millisecond
	NegativeScansBeforeAlign = 5
)
View Source
var MaxMemUsage uint64 = 2 * 1000 * 1000 * 1000
View Source
var (
	TimeFormat = "2006-01-02 15:04:05.00" // TimeFormat defines which timestamp to use with the logs
)

Functions

func Debug

func Debug(a ...any)

Debug is a shorthand for logger.DefaultLogger.Debug, see Logger interface method description for any information

func Fatal

func Fatal(a ...any)

Fatal creates a fatal log via the DefaultLogger and calls os.Exit(1)

func Fatalf

func Fatalf(format string, a ...any)

Fatald creates a fatal log via the DefaultLogger and calls os.Exit(1)

func IndentString

func IndentString(s string, n int) string

IndentString takes a string and indents every line with the provided number of single spaces

func LogsToJSON

func LogsToJSON(logs []Log) []byte

LogsToJSON converts a slice of logs in JSON format

func LogsToJSONIndented

func LogsToJSONIndented(logs []Log, spaces int) []byte

LogsToJSON converts a slice of logs in JSON format with the provided indentation length in spaces, not tabs

func PanicToErr

func PanicToErr(f func() error) error

PanicToErr is the same as PanicToErr but returns a plain error. This function can be used with every function via a function litteral. e.g.:

// let's use os.Open, with returns an *os.File and an error
var f *os.Open
err := logger.PanicToErr(func() error {
	var err error
	f, err = os.Open("/path/to/file")
	return err
}()

If the error was generated by a panic, che error by default will contain also the stack trace, but if you call the unwrap method, you will always get the shorter error.

func Print

func Print(level LogLevel, a ...any)

Print is a shorthand for logger.DefaultLogger.Print, see Logger interface method description for any information

func Printf

func Printf(level LogLevel, format string, a ...any)

Printf is a shorthand for logger.DefaultLogger.Printf, see Logger interface method description for any information

func RemoveTerminalColors

func RemoveTerminalColors(s string) string

RemoveTerminalColors strips every terminal color provided from this package from a string

func ToTerminal

func ToTerminal(out io.Writer) bool

ToTerminal tests if out is a terminal window or not

Types

type HugeLogger added in v2.2.0

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

func NewHugeLogger

func NewHugeLogger(out io.Writer, dir string, prefix string, tags ...string) (*HugeLogger, error)

NewLogger creates a logger that keeps in memory the most recent logs and saves everything in files divided in clusters. The dir parameter tells the logger in which directory to save the logs' files. The prefix, instead, tells the logger how to name the files. Read the Logger interface docs for other informations

func (*HugeLogger) AddLog added in v2.2.0

func (l *HugeLogger) AddLog(level LogLevel, message string, extra string, writeOutput bool) int

func (*HugeLogger) AsStderr added in v2.2.0

func (l *HugeLogger) AsStderr() io.Writer

func (*HugeLogger) AsStdout added in v2.2.0

func (l *HugeLogger) AsStdout() io.Writer

func (*HugeLogger) Clone added in v2.2.0

func (l *HugeLogger) Clone(out io.Writer, parentOut bool, tags ...string) Logger

func (*HugeLogger) Close added in v2.2.0

func (l *HugeLogger) Close()

func (*HugeLogger) Debug added in v2.2.0

func (l *HugeLogger) Debug(a ...any)

func (*HugeLogger) DisableExtras added in v2.2.0

func (l *HugeLogger) DisableExtras()

func (*HugeLogger) EnableExtras added in v2.2.0

func (l *HugeLogger) EnableExtras()

func (*HugeLogger) EnableHeavyLoadDetection added in v2.2.0

func (l *HugeLogger) EnableHeavyLoadDetection()

func (*HugeLogger) FixedLogger added in v2.2.0

func (l *HugeLogger) FixedLogger(level LogLevel) io.Writer

func (*HugeLogger) GetLastNLogs added in v2.2.0

func (l *HugeLogger) GetLastNLogs(n int) []Log

func (*HugeLogger) GetLastNLogsBuffered added in v2.2.0

func (l *HugeLogger) GetLastNLogsBuffered(n int) <-chan []Log

func (*HugeLogger) GetLog added in v2.2.0

func (l *HugeLogger) GetLog(index int) Log

func (*HugeLogger) GetLogs added in v2.2.0

func (l *HugeLogger) GetLogs(start, end int) []Log

func (*HugeLogger) GetLogsBuffered added in v2.2.0

func (l *HugeLogger) GetLogsBuffered(start, end int) <-chan []Log

func (*HugeLogger) GetSpecificLogs added in v2.2.0

func (l *HugeLogger) GetSpecificLogs(logs []int) []Log

func (*HugeLogger) NLogs added in v2.2.0

func (l *HugeLogger) NLogs() int

func (*HugeLogger) Out added in v2.2.0

func (l *HugeLogger) Out() io.Writer

func (*HugeLogger) Print added in v2.2.0

func (l *HugeLogger) Print(level LogLevel, a ...any)

func (*HugeLogger) Printf added in v2.2.0

func (l *HugeLogger) Printf(level LogLevel, format string, a ...any)

func (*HugeLogger) Write added in v2.2.0

func (l *HugeLogger) Write(p []byte) (n int, err error)

type Log

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

Log holds every information. It keeps the error severity level (see the constants), the time it was created at and the message associated with it. It also has the optional field "extra" that can be used to store additional information: Automatically everything after the first new line will be stored there. By default it will be displayed with an indentation, but you can hide it by calling the Logger method DisableExtras()

func LogsLevelMatch

func LogsLevelMatch(logs []Log, levels ...LogLevel) []Log

LogsLevelMatch returns the logs that match one of the severity levels provided

func LogsMatch

func LogsMatch(logs []Log, tags ...string) []Log

LogsMatch returns the logs that match every tag provided

func LogsMatchAny

func LogsMatchAny(logs []Log, tags ...string) []Log

LogsMatchAny returns the logs that match at least one of the tag provided

func (Log) Colored

func (l Log) Colored() string

Colored returns the message with the terminal decorations

func (Log) Date

func (l Log) Date() time.Time

func (Log) Extra

func (l Log) Extra() string

func (Log) Full

func (l Log) Full() string

Full return the message and the extras together

func (Log) FullColored

func (l Log) FullColored() string

FullColored return the message and the extras together with the terminal decorations

func (Log) ID

func (l Log) ID() string

func (Log) JSON

func (l Log) JSON() []byte

JSON returns the Log in a json-encoded string

func (Log) Level

func (l Log) Level() LogLevel

func (Log) LevelMatchAny

func (l Log) LevelMatchAny(levels ...LogLevel) bool

LevelMatchAny returns true if the Log has one of the log levels you have provided, otherwise returns false

func (Log) MarshalJSON

func (l Log) MarshalJSON() ([]byte, error)

func (Log) Match

func (l Log) Match(tags ...string) bool

Match returns true if the Log has every tag you have provided, otherwise returns false

func (Log) MatchAny

func (l Log) MatchAny(tags ...string) bool

MatchAny returns true if the Log has at least one of the tags you have provided, otherwise returns false

func (Log) Message

func (l Log) Message() string

func (Log) RawExtra

func (l Log) RawExtra() string

RawExtra returns the logger extra information (as the Extra() method) unmodified: see the method RawMessage() for other informations.

func (Log) RawMessage

func (l Log) RawMessage() string

RawMessage returns the logger message (as the Message() method) unmodified: if the Logger output is a terminal, the logger will automatically decorate the message with terminal colors. This method gives you back not only the message but also every terminal character for the color-handling

func (Log) String

func (l Log) String() string

func (Log) Tags

func (l Log) Tags() []string

func (*Log) UnmarshalJSON

func (l *Log) UnmarshalJSON(data []byte) error

type LogLevel

type LogLevel int

LogLevel defines the severity of a Log. See the constants

const (
	LOG_LEVEL_BLANK LogLevel = iota
	LOG_LEVEL_INFO
	LOG_LEVEL_DEBUG
	LOG_LEVEL_WARNING
	LOG_LEVEL_ERROR
	LOG_LEVEL_FATAL
)

func (LogLevel) MarshalJSON

func (level LogLevel) MarshalJSON() ([]byte, error)

func (LogLevel) String

func (level LogLevel) String() string

func (*LogLevel) UnmarshalJSON

func (level *LogLevel) UnmarshalJSON(b []byte) error

type Logger

type Logger interface {
	// AddLog can be used to manually create a Log, writeOutput can be set to false
	// if you also want the log to not be written to the io.Writer associated with
	// the Logger
	AddLog(level LogLevel, message string, extra string, writeOutput bool) int
	// Clone creates a pseudo-Logger that leans on the calling Logger, called the parent logger.
	// You can specify additional tags that will be inherited by every log created with
	// this logger, in addition to every tags owned by the parent logger. If you specify an out
	// io.Writer, every log will be also writter to this destination, and if you set parentOut to
	// true every log will be also written by the parent on its own output, possibly creating
	// multiple logs lines if the output is the same
	Clone(out io.Writer, parentOut bool, tags ...string) Logger
	// Debug is a shorthand for Print(logger.LOG_LEVEL_DEBUG, a...), can be handy while debugging
	// some code. See interface method Print for more information
	Debug(a ...any)
	// DisableExtras tells the Logger to not write the Extra field of the Logs created to the
	// out io.Writer (it will always be saved, so it can be accessed manually)
	DisableExtras()
	// EnableExtras tells the Logger to write the Extra field of the Logs created to the
	// out io.Writer. This is the default behaviour
	EnableExtras()
	// GetLastNLogs return the last Logs created by the Logger. If the number of logs asked is
	// greater than the total amount of logs created, the method will return every log saved
	// without errors
	GetLastNLogs(n int) []Log
	// GetLog returns a specific Log: being the "0" log the first created and the "nth-1" log the
	// nth created. Use the method NLogs() to know the total number of logs saved. It's not safe
	// to call it with an out-of-range index
	GetLog(index int) Log
	// GetLogs return every log in the interval [start ; end). It's not safe to call it with out-of-range
	// values
	GetLogs(start int, end int) []Log
	// GetSpecificLogs can be used to retrieve a list of logs. The argument holds the indexes of the
	// logs wanted
	GetSpecificLogs(logs []int) []Log

	// NLogs returns the number of logs saved in the logger
	NLogs() int
	// Out returns the same io.Writer provided at creation time
	Out() io.Writer
	// Print behaves has the fmt.Print or log.Print from the standard library, but if
	// the resulting output contains a line feed, everything after that will be used to
	// populate the extra field of the Log
	Print(level LogLevel, a ...any)
	// Printf behaves has the fmt.Printf or log.Printf from the standard library, but if
	// the resulting output contains a line feed, everything after that will be used to
	// populate the extra field of the Log
	Printf(level LogLevel, format string, a ...any)
	AsStdout() io.Writer
	AsStderr() io.Writer
	FixedLogger(level LogLevel) io.Writer
	Write(p []byte) (n int, err error)
	EnableHeavyLoadDetection()
	Close()
	// contains filtered or unexported methods
}

Logger handles the logging. There are three types of Logger, depending on the way they save the logs: NewLogger() creates a Logger which saved every log in memory, NewHugeLogger() creates a Logger which keeps the most recent logs in memory and saves every logs in the filesystem, the method Clone() of every Logger creates a pseudo-Logger. You can read more in the package documentation for other info and usage senarios. For every Logger type, there is an io.Writer, which can be used to specify where to write the logs, and a list of tags, which will be given to every Log created with this Logger (in this way you can implement a filter to get only the logs you need). Logger also implements the io.Writer interface, so can be used to use it as a standard output: every write call corresponds to a Log with level logger.LOG_LEVEL_BLANK

var DefaultLogger Logger

DefaultLogger is the Logger used by the function in this package (like logger.Print, logger.Debug, ecc) and is initialized as a standard logger (logs are saved only in memory). Can be changed at any time and every process using this logger will reflect the change

func NewLogger

func NewLogger(out io.Writer, tags ...string) Logger

NewLogger creates a standard logger, which saves the logs only in memory. Read the Logger interface docs for other informations

type PanicError

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

PanicError is used by the functions CapturePanic and PanicToErr to capture any function returning an error and any generated panic. If Err is set, it means that the function returned an error without panicking, instead if PanicErr is set, it means that the function returned prematurely due to a panic: the PanicErr is set and the stack trace can be accessed via the Stack method. It also implements the error interface and the Unwrap method. See the Error method for more information on this

func CapturePanic

func CapturePanic(f func() error) (panicErr *PanicError)

CapturePanic runs any function that returns an error in a panic-controlled environment and converts any panic (if any) into an error. Expecially, the error generated by a panic can be unwrapped to get rid of the stack trace ( or manipulated to separate the error from the stack trace). In reality, it can be used with any function via a function litteral, e.g.:

// let's use os.Open, with returns an *os.File and an error
var f *os.Open
panicErr := logger.CapturePanic(func() error {
	var err error
	f, err = os.Open("/path/to/file")
	return err
}()

func (PanicError) Err

func (p PanicError) Err() error

Err return the error, if any, returned by a function

func (PanicError) Error

func (err PanicError) Error() string

func (PanicError) PanicErr

func (p PanicError) PanicErr() error

PanicErr return the error associated with the panic of a function, if any

func (PanicError) Stack

func (p PanicError) Stack() string

Stack returns the stack trace associated with a panic. If no panic has occurred, it will return an empty string

func (PanicError) String

func (err PanicError) String() string

func (PanicError) Unwrap

func (err PanicError) Unwrap() error

Jump to

Keyboard shortcuts

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