logze

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2024 License: MIT Imports: 12 Imported by: 0

README

logze

GoDoc Build GoReport

Package logze implements a zerolog wrapper providing a convenient and short interface for structural logging

Install: go get github.com/maxbolgarin/logze

Why you should try

If you want to log an error in zerolog, you will write something like this:

log.Error().Err(err).Str("address", "127.0.0.1").Msg("cannot start server")

This is a quite long piece of code. You also should remember all of these methods. Let's look at a logze example:

logze.Error(err, "cannot start server", "address", "127.0.0.1")

Firstly, it is shorter. Secondly, you call only one method, which calls Error. That is quite intuitive — if you want to log error, you will use Error method.

In other hand, you may say, that it is better to use slog with the similar interface instead of logze. But logze provides a zerolog efficency with a convinient interface.

How to use

  1. Firstly, you should create a new logger or init a global one: use New function or Init
  2. To create a new logger, you should provide it a Config: use NewConfig and With* methods
  3. After creating a new logger, you can use it's methods. Their names match the names of the logging levels, e.g. Debug or Error
  4. To log formatted message, use methods with f suffix. You can also add field pairs to such formatted messages, just add them after format args, like: logze.Infof("msg: %s", variable, "key", "value")

Warning! Pretty logging on the console is made possible using the provided WithConsole() method in Config, but it is inefficient. Use WithConsoleJSON or NewConfig(os.Stderr) to use all zerolog advantages.

Local logger example
	// Create a new logger instance with pretty logging to console (useful for developing)
	lg := logze.New(logze.NewConfig().WithConsole())

	// Log a debug message
	lg.Debug("some debug message")

	// Create a new logger with fields, that will be added to all log messages
	lg = lg.WithFields("foo", "bar")

	// Example of formatting and adding fields simultaniously
	a := "message"
	lg.Infof("some info message with format %s", a, "key", "value")


	// Here is the result
	// 2024-09-18 22:00:54 DBG some debug message
	// 2024-09-18 22:00:55 INF some info message with format message key=value foo=bar

Global logger example

	// Init global logger with trace level and one field pair
	logze.Init(logze.NewConfig().WithConsole().WithLevel(logze.TraceLevel), "foo", "bar")

	// Trace log will print Caller
	logze.Trace("trace message")

	// Example of logging an error
	logze.Error(errm.New("some_error"), "message")


	// Here is the result	
	// 10:32:57 TRC test/main.go:16 > trace message foo=bar
	// 10:32:57 ERR message error=some_error foo=bar

Contributing

If you'd like to contribute to logze, make a fork and submit a pull request!

Released under the MIT License

Documentation

Overview

Package logze implements a zerolog wrapper providing a convenient and short interface for structural logging.

Index

Constants

View Source
const (
	TraceLevel    = "trace"
	DebugLevel    = "debug"
	InfoLevel     = "info"
	WarnLevel     = "warn"
	ErrorLevel    = "error"
	FatalLevel    = "fatal"
	DisabledLevel = "disabled"
)

Enumerating string representations of all supported levels.

View Source
const DefaultDiodeSize = 1000

DefaultDiodeSize is a default size of a diode writer. Logs will be lost if there will be more logs than that value in a small period of time (of time less that Config.DiodePollingInterval).

Variables

Levels is a list of all supported levels in string format.

LevelsAny is a list of all supported levels in any format.

View Source
var Log = NewDefault()

Log is a global logger.

Functions

func Debug

func Debug(msg string, fields ...any)

Debug logs a message in debug level adding provided fields using a global logger.

func Debugf

func Debugf(msg string, args ...any)

Debugf logs a formatted message in debug level adding provided fields after formatting args using a global logger.

func Err

func Err(err error, fields ...any)

Err logs a provided error in error level adding provided fields using a global logger.

func Error

func Error(err error, msg string, fields ...any)

Error logs a provided error and message in error level adding provided fields using a global logger.

func Errorf

func Errorf(err error, msg string, args ...any)

Errorf logs a provided error and formatted message in error level adding provided fields after formatting args using a global logger.

func Fatal

func Fatal(v ...any)

Fatal logs a message in fatal level using fmt.Sprint to interpret args sing a global logger, then calls os.Exit(1).

func Fatalf

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

Fatalf logs a formatted message in fatal level using a global logger, then calls os.Exit(1).

func Fatalln

func Fatalln(v ...any)

Fatalln logs a message in fatal level using fmt.Sprintln to interpret args using a global logger, then calls os.Exit(1).

func Info

func Info(msg string, fields ...any)

Info logs a message in info level adding provided fields using a global logger.

func Infof

func Infof(msg string, args ...any)

Infof logs a formatted message in info level adding provided fields after formatting args using a global logger.

func Init

func Init(cfg Config, fields ...any)

Init calls New function and assigns the result to global Log variable. It also calls SetLoggerForDefault with this new logger.

func Panic

func Panic(v ...any)

Panic logs a message in fatal level using fmt.Sprint to interpret args using a global logger, then calls panic().

func Panicf

func Panicf(format string, args ...any)

Panicf logs a formatted message in fatal level using a global logger, then calls panic().

func Panicln

func Panicln(v ...any)

Panicln logs a message in fatal level using fmt.Sprintln to interpret args using a global logger, then calls panic().

func Print

func Print(v ...any)

Print logs a message without level using fmt.Sprint to interpret args using a global logger.

func Printf

func Printf(format string, args ...any)

Printf logs a formatted message without level using a global logger.

func Println

func Println(v ...any)

Println writes a message without level using fmt.Sprintln to interpret args using a global logger.

func Raw

func Raw() *zerolog.Logger

Raw returns Logger's underlying zerolog.Logger from global logger.

func SetLoggerForDefault

func SetLoggerForDefault(l Logger, fields ...any)

SetLoggerForDefault sets priovded Logger with (key, value) pairs as writer for default Go logger and also calls stdlog.SetFlags(0).

func Trace

func Trace(msg string, fields ...any)

Trace logs a message in trace level adding provided fields and information about method caller using a global logger.

func Tracef

func Tracef(msg string, args ...any)

Tracef logs a formatted message in trace level adding provided fields after formatting args and information about method caller using a global logger.

func Update added in v1.3.0

func Update(cfg Config, fields ...any)

Update calls Logger.Update method for global Log. It also calls SetLoggerForDefault with this new logger. It is not safe for concurrent use!

func Warn

func Warn(msg string, fields ...any)

Warn logs a message in warning level adding provided fields using a global logger.

func Warnf

func Warnf(msg string, args ...any)

Warnf logs a formatted message in warn level adding provided fields after formatting args using a global logger.

func Write

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

Write writes bytes to underlying io.Writer using a global logger.

Types

type Config

type Config struct {
	// Writers is a list of writers where logger will log its data.
	// Default value is [io.Discard].
	Writers []io.Writer

	// Level is a log level in string format. Supported levels are:
	// trace, debug, info, warn, error, fatal, disabled.
	Level string

	// Hook is a zerolog.Hook that will be used when creating logger.
	// Default value is nil.
	Hook zerolog.Hook

	// ToIgnore is a list of messages that will be ignored.
	// Default value is nil.
	ToIgnore []string

	// ErrorCounter is a counter of logged errors. Use WithSimpleErrorCounter method to use a simple counter.
	// Default value is nil.
	ErrorCounter ErrorCounter

	// DiodeSize is a size of a diode writer. Logs will be lost if there will be more logs than that value
	// in a small period of time (of time less that Config.DiodePollingInterval).
	// Default value is 1000.
	DiodeSize int

	// DiodePollingInterval is a time after which diode writer will flush its buffer.
	// Default value is 100ms.
	DiodePollingInterval time.Duration

	// DiodeAlertFunc is a function that will be called when diode writer will flush its buffer.
	// Default value is a function that logs a message in warn level.
	DiodeAlertFunc func(int)

	// DisableDiode if true, will disable diode writer.
	// Default value is false.
	DisableDiode bool

	// StackTrace if true, will enable stack trace for Error and Errorf methods.
	// Default value is false.
	StackTrace bool
}

Config is using for initializing Logger. You should use NewConfig and With* methods instead of creating a Config struct directly.

func NewConfig

func NewConfig(writers ...io.Writer) Config

NewConfig returns Config with provided list of io.Writer, where Logger should logs its data.

func (Config) WithConsole

func (c Config) WithConsole() Config

WithConsole returns Config with a configurated output to stderr in a pretty console format with colors. This format may significantly slow down logging in an application compared to a default JSON format.

func (Config) WithConsoleJSON

func (c Config) WithConsoleJSON() Config

WithConsoleJSON returns Config with a configurated output to stderr in a JSON format.

func (Config) WithConsoleNoColor

func (c Config) WithConsoleNoColor() Config

WithConsoleNoColor returns Config a with configurated output to stderr in a pretty console format without colors. This format may significantly slow down logging in an application compared to a default JSON format.

func (Config) WithDiodeAlert

func (c Config) WithDiodeAlert(foo func(int)) Config

WithDiodeAlert returns Config with provided diode alert func.

func (Config) WithDiodePollingInterval

func (c Config) WithDiodePollingInterval(interval time.Duration) Config

WithDiodePollingInterval returns Config with enabled diode polling with provided interval.

func (Config) WithDiodeSize

func (c Config) WithDiodeSize(size int) Config

WithDiodeSize returns Config with a new size of diode writer.

func (Config) WithDisabledDiode

func (c Config) WithDisabledDiode() Config

WithDisabledDiode returns Config with disabled diode writer.

func (Config) WithErrorCounter

func (c Config) WithErrorCounter(ec ErrorCounter) Config

WithErrorCounter returns Config with the provided ErrorCounter.

func (Config) WithHook

func (c Config) WithHook(hook zerolog.Hook) Config

WithHook returns Config with initialized zerolog.Hook provided as argument.

func (Config) WithLevel

func (c Config) WithLevel(level string) Config

WithLevel returns Config with initialized level (in string format) provided as argument.

func (Config) WithSimpleErrorCounter

func (c Config) WithSimpleErrorCounter(name string) Config

WithErrorCounter returns Config with a simple ErrorCounter inited with the provided name.

func (Config) WithStackTrace

func (c Config) WithStackTrace() Config

WithStackTrace returns Config with an enabled stack trace for Error and Errorf methods.

func (Config) WithToIgnore added in v1.2.0

func (c Config) WithToIgnore(toIgnore ...string) Config

WithToIgnore returns Config with a list of messages that will be ignored.

func (Config) WithWriter

func (c Config) WithWriter(w io.Writer) Config

WithWriter returns Config with added provided io.Writer to a list of writers.

type ErrorCounter

type ErrorCounter interface {
	Name() string
	Inc()
	Get() int64
}

ErrorCounter provides an interface to count logged errors. Every ErrorCounter should be created with a name to distinguish in what part of the program an error was occurred. Use WithSimpleErrorCounter in Config creation to use a simple error counter and GetErrorCounter method in Logger to retrieve it.

func GetErrorCounter

func GetErrorCounter() ErrorCounter

GetErrorCounter returns Logger's underlying ErrorCounter from global logger.

type Logger

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

Logger represents an initialized logger. Default value behaves as default zerolog.Logger.

func New

func New(cfg Config, fields ...any) Logger

New returns a new Logger with provided config and fields.

  • Default output is io.Discard, so you should provide at least one io.Writer in Config when creating a logger.
  • Default level is info.
  • Fields should be passed as (key, value) pairs, its will be applied to all messages.

For example, if you use Logger like that:

lg := New(NewConfig().WithConsoleJSON(), "foo", "bar")
lg.Info("some message", "key", "value")
lg.Error(errors.New("some error"), "cannot handle")

You will have output:

{"level":"info","time":"2023-11-20T18:48:14+03:00","message":"some message","foo":"bar","key":"value"}
{"level":"error","time":"2023-11-20T18:48:14+03:00","error":"some error","message":"cannot handle","foo":"bar"}

func NewDefault

func NewDefault(fields ...any) Logger

NewDefault returns a new Logger with logging to stderr.

func Nop added in v1.3.0

func Nop() Logger

Nop returns a new Logger with no logging.

func With added in v1.3.0

func With(fields ...any) Logger

With is a shortcut for WithFields.

func WithErrorCounter

func WithErrorCounter(ec ErrorCounter) Logger

WithErrorCounter returns Logger with the provided ErrorCounter, based on a global logger.

func WithFields

func WithFields(fields ...any) Logger

WithFields returns Logger with applied fields, provided as (key, value) pairs, based on a global logger.

func WithLevel

func WithLevel(level string) Logger

WithLevel returns Logger with applied log level, based on a global logger.

func WithSimpleErrorCounter

func WithSimpleErrorCounter(name string) Logger

WithSimpleErrorCounter returns Logger with a simple ErrorCounter inited with the provided name, based on a global logger.

func (Logger) Debug

func (l Logger) Debug(msg string, fields ...any)

Debug logs a message in debug level adding provided fields.

func (Logger) Debugf

func (l Logger) Debugf(msg string, args ...any)

Debugf logs a formatted message in debug level adding provided fields after formatting args.

func (Logger) Err

func (l Logger) Err(err error, fields ...any)

Err logs a provided error in error level adding provided fields.

func (Logger) Error

func (l Logger) Error(err error, msg string, fields ...any)

Error logs a provided error and message in error level adding provided fields.

func (Logger) Errorf

func (l Logger) Errorf(err error, msg string, args ...any)

Errorf logs a provided error and formatted message in error level adding provided fields after formatting args.

func (Logger) Fatal

func (l Logger) Fatal(v ...any)

Fatal logs a message in fatal level using fmt.Sprint to interpret args, then calls os.Exit(1).

func (Logger) Fatalf

func (l Logger) Fatalf(format string, args ...any)

Fatalf logs a formatted message in fatal level, then calls os.Exit(1).

func (Logger) Fatalln

func (l Logger) Fatalln(v ...any)

Fatalln logs a message in fatal level using fmt.Sprintln to interpret args, then calls os.Exit(1).

func (Logger) GetErrorCounter

func (l Logger) GetErrorCounter() ErrorCounter

GetErrorCounter returns Logger's underlying ErrorCounter.

func (Logger) Info

func (l Logger) Info(msg string, fields ...any)

Info logs a message in info level adding provided fields.

func (Logger) Infof

func (l Logger) Infof(msg string, args ...any)

Infof logs a formatted message in info level adding provided fields after formatting args.

func (Logger) NotInited added in v1.1.0

func (l Logger) NotInited() bool

NotInited returns true if Logger is not inited (struct with default values).

func (Logger) Panic

func (l Logger) Panic(v ...any)

Panic logs a message in fatal level using fmt.Sprint to interpret args, then calls panic().

func (Logger) Panicf

func (l Logger) Panicf(format string, args ...any)

Panicf logs a formatted message in fatal level, then calls panic().

func (Logger) Panicln

func (l Logger) Panicln(v ...any)

Panicln logs a message in fatal level using fmt.Sprintln to interpret args, then calls panic().

func (Logger) Print

func (l Logger) Print(v ...any)

Print logs a message without level using fmt.Sprint to interpret args.

func (Logger) Printf

func (l Logger) Printf(format string, args ...any)

Printf logs a formatted message without level.

func (Logger) Println

func (l Logger) Println(v ...any)

Println writes a message without level using fmt.Sprintln to interpret args.

func (Logger) Raw

func (l Logger) Raw() *zerolog.Logger

Raw returns Logger's underlying zerolog.Logger.

func (Logger) Trace

func (l Logger) Trace(msg string, fields ...any)

Trace logs a message in trace level adding provided fields and information about method caller.

func (Logger) Tracef

func (l Logger) Tracef(msg string, args ...any)

Tracef logs a formatted message in trace level adding provided fields after formatting args and information about method caller.

func (*Logger) Update added in v1.3.0

func (l *Logger) Update(cfg Config, fields ...any)

Update replaces underlying logger with a new one created using provided config and fields. It is not safe for concurrent use!

func (Logger) Warn

func (l Logger) Warn(msg string, fields ...any)

Warn logs a message in warning level adding provided fields.

func (Logger) Warnf

func (l Logger) Warnf(msg string, args ...any)

Warnf logs a formatted message in warn level adding provided fields after formatting args.

func (Logger) With added in v1.3.0

func (l Logger) With(fields ...any) Logger

With is a shortcut for Logger.WithFields.

func (Logger) WithErrorCounter

func (l Logger) WithErrorCounter(ec ErrorCounter) Logger

WithErrorCounter returns Logger with the provided ErrorCounter.

func (Logger) WithFields

func (l Logger) WithFields(fields ...any) Logger

WithFields returns Logger with applied fields to all messages, provided as (key, value) pairs.

func (Logger) WithLevel

func (l Logger) WithLevel(level string) Logger

WithLevel returns Logger with an applied log level.

func (Logger) WithSimpleErrorCounter

func (l Logger) WithSimpleErrorCounter(name string) Logger

WithSimpleErrorCounter returns Logger with a simple ErrorCounter inited with the provided name.

func (Logger) WithStack

func (l Logger) WithStack(stackTrace bool) Logger

WithStack returns Logger with an applied stackTrace.

func (Logger) Write

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

Write writes bytes to underlying io.Writer.

type SLogger added in v1.1.0

type SLogger struct {
	Logger
}

SLogger is a wrapper for Logger. It provides the same methods as Logger but with another Error interface (slog style).

func ConvertToS added in v1.1.0

func ConvertToS(l Logger) SLogger

ConvertToS converts Logger to SLogger.

func (SLogger) Error added in v1.1.0

func (l SLogger) Error(msg string, fields ...any)

Error logs a message in error level adding provided fields.

func (SLogger) Errorf added in v1.1.0

func (l SLogger) Errorf(msg string, fields ...any)

Errorf logs a formatted message in error level adding provided fields after formatting args.

Jump to

Keyboard shortcuts

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