logger

package module
v0.0.0-...-71e4ee1 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2024 License: MIT Imports: 17 Imported by: 16

README

Logger

A simple prefixer logger that can wrap several backends. The formatters/handlers from this repository must be used in order to make prefix work.

Interface

type Logger interface {
	WithPrefix(prefix string) Logger
	WithPrefixf(format string, args ...interface{}) Logger
	WithField(key string, value interface{}) Logger
	WithError(error error) Logger
	WithFields(fields map[string]interface{}) Logger
	//
	Debug(args ...interface{})
	Debugf(format string, args ...interface{})
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Warn(args ...interface{})
	Warnf(format string, args ...interface{})
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	//
	Print(args ...interface{})
	Printf(format string, args ...interface{})
	Println(args ...interface{})
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
	Fatalln(args ...interface{})
	Panic(args ...interface{})
	Panicf(format string, args ...interface{})
	Panicln(args ...interface{})
}

Backends

Helpers

  • type M map[string]interface{} used as a shorthand for a map of interfaces used by WithFields method
  • func WithLogger(ctx context.Context, l Logger) context.Context to embeds the logger inside a context
  • func LogWith(ctx context.Context) Logger to extract a logger from a context

License

MIT

Contributing

All PRs are welcome.

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Documentation

Index

Constants

View Source
const KeyPrefix = "__prefix"

A KeyPrefix is used to tell that en given attr/field is a prefix.

Variables

This section is empty.

Functions

func ParseSlogLevel

func ParseSlogLevel(lvl string) (slog.Level, error)

ParseSlogLevel takes a string level and returns the slog.Level constant.

func WithLogger

func WithLogger(ctx context.Context, l Logger) context.Context

WithLogger returns a new context that embeds the given logger.

Types

type BufferGELF

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

A BufferGELF is a buffer used to build GELF payload.

func NewBufferGELF

func NewBufferGELF() *BufferGELF

NewBufferGELF returns a new BufferGELF.

func (*BufferGELF) Add

func (b *BufferGELF) Add(k string, v any)

Add adds any key/value to the GELF buffer.

func (*BufferGELF) Bytes

func (b *BufferGELF) Bytes() []byte

Bytes returns the bytes of the current GELF payload state.

func (*BufferGELF) Complete

func (b *BufferGELF) Complete(ln bool) []byte

Complete returns the completed GELF payload with a `\n' when ln is true.

func (*BufferGELF) Host

func (b *BufferGELF) Host(h string)

Host adds the host to the GELF buffer.

func (*BufferGELF) Level

func (b *BufferGELF) Level(l int32)

Level adds the level to the GELF buffer.

func (*BufferGELF) Message

func (b *BufferGELF) Message(m string)

Message adds the short_message/full_message to the GELF buffer.

func (*BufferGELF) Timestamp

func (b *BufferGELF) Timestamp(t time.Time)

Timestamp adds the timestamp to the GELF buffer.

type ColorScheme

type ColorScheme struct {
	InfoLevelStyle  string
	WarnLevelStyle  string
	ErrorLevelStyle string
	FatalLevelStyle string
	PanicLevelStyle string
	DebugLevelStyle string
	PrefixStyle     string
	TimestampStyle  string
}

type ContextKey

type ContextKey string

A ContextKey is used to add data into a context.Context.

const LoggerKey ContextKey = "_logger"

LoggerKey is the storing key used for storing and retrieve the logger from a context.

type Logger

type Logger interface {
	WithPrefix(prefix string) Logger
	WithPrefixf(format string, args ...any) Logger
	WithField(key string, value any) Logger
	WithError(error error) Logger
	WithFields(fields map[string]any) Logger
	//
	Debug(args ...any)
	Debugf(format string, args ...any)
	Info(args ...any)
	Infof(format string, args ...any)
	Warn(args ...any)
	Warnf(format string, args ...any)
	Error(args ...any)
	Errorf(format string, args ...any)
	//
	Print(args ...any)
	Printf(format string, args ...any)
	Println(args ...any)
	Fatal(args ...any)
	Fatalf(format string, args ...any)
	Fatalln(args ...any)
	Panic(args ...any)
	Panicf(format string, args ...any)
	Panicln(args ...any)
}

A Logger is the interface used in this package for logging, so that any backend can be plugged in.

func LogWith

func LogWith(ctx context.Context) Logger

LogWith returns the logger extracted from the context. It panics if no logger inside the context.

func NewNullLogger

func NewNullLogger() Logger

NewNullLogger returns null Logger.

func WrapLogrus

func WrapLogrus(l *logrus.Logger) Logger

WrapLogrus returns Logger based on Logrus backend.

func WrapSlog

func WrapSlog(l *slog.Logger) Logger

WrapSlog returns Logger based on log/slog backend.

func WrapSlogHandler

func WrapSlogHandler(h slog.Handler) Logger

WrapSlogHandler returns Logger based on log/slog's handler backend.

type LogrusGELFFormatter

type LogrusGELFFormatter struct {
	sync.Once
	Hostname string
}

A LogrusGELFFormatter is GELF formatter for Logrus.

func (*LogrusGELFFormatter) Format

func (f *LogrusGELFFormatter) Format(entry *logrus.Entry) ([]byte, error)

Format implements logrus.Formatter.

type LogrusTextFormatter

type LogrusTextFormatter struct {
	// Set to true to bypass checking for a TTY before outputting colors.
	ForceColors bool

	// Force disabling colors. For a TTY colors are enabled by default.
	DisableColors bool

	// Force formatted layout, even for non-TTY output.
	ForceFormatting bool

	// Disable timestamp logging. useful when output is redirected to logging
	// system that already adds timestamps.
	DisableTimestamp bool

	// Disable the conversion of the log levels to uppercase
	DisableUppercase bool

	// Enable logging the full timestamp when a TTY is attached instead of just
	// the time passed since beginning of execution.
	FullTimestamp bool

	// Timestamp format to use for display when a full timestamp is printed.
	TimestampFormat string

	// The fields are sorted by default for a consistent output. For applications
	// that log extremely frequently and don't use the JSON formatter this may not
	// be desired.
	DisableSorting bool

	// Wrap empty fields in quotes if true.
	QuoteEmptyFields bool

	// Can be set to the override the default quoting character "
	// with something else. For example: ', or `.
	QuoteCharacter string

	// Pad msg field with spaces on the right for display.
	// The value for this parameter will be the size of padding.
	// Its default value is zero, which means no padding will be applied for msg.
	SpacePadding int

	// Regexp to find prefix to be colored.
	// If not defined, no coloration is applied.
	// e.g. Use `^(\[.*?\])\s` to colorize prefix for message like "[prefix#1][prefix#2] The message"
	PrefixRE *regexp.Regexp

	// ValueFormatter is the format of the value when logs are pretty printed.
	// The default value is `%v'. You can use `%+v' to print the stacktrace of github.com/pkg/errors.
	ValueFormatter string

	sync.Once
	// contains filtered or unexported fields
}

A LogrusTextFormatter is pretty printer for Logrus. It supports github.com/mdouchement/logger prefix. Borrowed from https://github.com/x-cray/logrus-prefixed-formatter.

func (*LogrusTextFormatter) Format

func (f *LogrusTextFormatter) Format(entry *logrus.Entry) ([]byte, error)

Format implements logrus.Formatter.

func (*LogrusTextFormatter) SetColorScheme

func (f *LogrusTextFormatter) SetColorScheme(colorScheme *ColorScheme)

SetColorScheme setup the color scheme.

type M

type M map[string]any

M defines a generic map of type `map[string]interface{}`.

type SlogGELFHandler

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

A SlogGELFHandler is GELF formatter for log/slog.

func NewSlogGELFHandler

func NewSlogGELFHandler(w io.Writer, o *SlogGELFOption) *SlogGELFHandler

NewSlogGELFHandler returns a new SlogGELFHandler.

func (*SlogGELFHandler) Clone

func (h *SlogGELFHandler) Clone() *SlogGELFHandler

Clone clones the entry, it creates a new instance and linking the parent to it.

func (*SlogGELFHandler) Enabled

func (h *SlogGELFHandler) Enabled(_ context.Context, l slog.Level) bool

Enabled reports whether the handler handles records at the given level.

func (*SlogGELFHandler) Handle

func (h *SlogGELFHandler) Handle(_ context.Context, record slog.Record) error

Handle handles the Record.

func (*SlogGELFHandler) WithAttrs

func (h *SlogGELFHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new Handler whose attributes consist of both the receiver's attributes and the arguments.

func (*SlogGELFHandler) WithGroup

func (h *SlogGELFHandler) WithGroup(name string) slog.Handler

WithGroup returns a new Handler with the given group appended to the receiver's existing groups.

type SlogGELFOption

type SlogGELFOption struct {
	Level    slog.Level
	Hostname string
}

A SlogGELFOption holds SlogGELFHandler's options.

type SlogTextHandler

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

A SlogTextHandler is Logrus text formatter for log/slog.

func NewSlogTextHandler

func NewSlogTextHandler(w io.Writer, o *SlogTextOption) *SlogTextHandler

NewSlogTextHandler returns a new SlogTextHandler.

func (*SlogTextHandler) Clone

func (h *SlogTextHandler) Clone() *SlogTextHandler

func (*SlogTextHandler) Enabled

func (h *SlogTextHandler) Enabled(_ context.Context, l slog.Level) bool

Enabled reports whether the handler handles records at the given level.

func (*SlogTextHandler) Handle

func (h *SlogTextHandler) Handle(_ context.Context, record slog.Record) error

Handle handles the Record.

func (*SlogTextHandler) WithAttrs

func (h *SlogTextHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new Handler whose attributes consist of both the receiver's attributes and the arguments.

func (*SlogTextHandler) WithGroup

func (h *SlogTextHandler) WithGroup(name string) slog.Handler

WithGroup returns a new Handler with the given group appended to the receiver's existing groups.

type SlogTextOption

type SlogTextOption struct {
	// Set the logger's level.
	Level slog.Level

	// Set to true to bypass checking for a TTY before outputting colors.
	ForceColors bool

	// Force disabling colors. For a TTY colors are enabled by default.
	DisableColors bool

	// Force formatted layout, even for non-TTY output.
	ForceFormatting bool

	// Disable timestamp logging. useful when output is redirected to logging
	// system that already adds timestamps.
	DisableTimestamp bool

	// Disable the conversion of the log levels to uppercase
	DisableUppercase bool

	// Enable logging the full timestamp when a TTY is attached instead of just
	// the time passed since beginning of execution.
	FullTimestamp bool

	// Timestamp format to use for display when a full timestamp is printed.
	TimestampFormat string

	// The fields are sorted by default for a consistent output. For applications
	// that log extremely frequently and don't use the JSON formatter this may not
	// be desired.
	DisableSorting bool

	// Wrap empty fields in quotes if true.
	QuoteEmptyFields bool

	// Can be set to the override the default quoting character "
	// with something else. For example: ', or `.
	QuoteCharacter string

	// Pad msg field with spaces on the right for display.
	// The value for this parameter will be the size of padding.
	// Its default value is zero, which means no padding will be applied for msg.
	SpacePadding int

	// Regexp to find prefix to be colored.
	// If not defined, no coloration is applied.
	// e.g. Use `^(\[.*?\])\s` to colorize prefix for message like "[prefix#1][prefix#2] The message"
	PrefixRE *regexp.Regexp

	// ValueFormatter is the format of the value when logs are pretty printed.
	// The default value is `%v'. You can use `%+v' to print the stacktrace of github.com/pkg/errors.
	ValueFormatter string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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