logger

package module
v3.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 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.
	// The default value (100_000) is a good compromise between memory
	// usage and operations speed, considering that each chunk of logs
	// takes 5MB of memory with this value
	LogChunkSize = 100_000
	// LogFileExtension can be used to change the file extenstion of the
	// log files
	LogFileExtension                = "data"
	MaxLogsPerScan                  = 200
	ScanInterval                    = 200 * time.Millisecond
	NegativeScansBeforeAlign        = 5
	AlignChunkSize                  = 1_000
	MaxMemUsage              uint64 = 1_000_000_000
)
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 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 struct {
	TrimFunc func(string) string
	// contains filtered or unexported fields
}
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 NewHugeLogger

func NewHugeLogger(out io.Writer, dir string, prefix string, tags ...string) (*Logger, 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 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

func (*Logger) AddLog

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

func (*Logger) AsStderr

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

func (*Logger) AsStdout

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

func (*Logger) Clone

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

func (*Logger) Close added in v3.0.3

func (l *Logger) Close()

func (*Logger) Debug

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

func (*Logger) DisableExtras

func (l *Logger) DisableExtras()

func (*Logger) DisableHeavyLoad

func (l *Logger) DisableHeavyLoad()

func (*Logger) EnableExtras

func (l *Logger) EnableExtras()

func (*Logger) EnableHeavyLoad

func (l *Logger) EnableHeavyLoad()

func (*Logger) FixedLogger

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

func (*Logger) GetLastNLogs

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

func (*Logger) GetLastNLogsBuffered

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

func (*Logger) GetLog

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

func (*Logger) GetLogs

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

func (*Logger) GetLogsBuffered

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

func (*Logger) GetSpecificLogs

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

func (*Logger) ListenForLogs added in v3.0.3

func (l *Logger) ListenForLogs(bufSize int) (int, *broadcaster.Channel[Log])

func (*Logger) Logs

func (l *Logger) Logs() int

func (*Logger) Out

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

func (*Logger) Print

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

func (*Logger) Printf

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

func (*Logger) Write

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

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