logger

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2021 License: Apache-2.0 Imports: 10 Imported by: 1

README

About

This package is a library of go project. This is a zero-dependency standard JSON log library that supports structured JSON logs and is compatible with the standard library.

  • Flexible and controllable caller report.
  • Support 7 log levels.
  • Complete log standard library compatibility.
  • Chained call, supporting additional log context data.
  • Flexible log hook support.
  • Custom log formatter support.

Install

go get -u -v gitee.com/allan577/go-lib-logger

Usage

package main

import (
    "gitee.com/allan577/go-lib-logger"
)

func main() {
    // Creates a logger instance with the specified name.
    log := logger.New("test")

    // {"level":"info","message":"Something happened.","name":"test","time":"2020-02-20T20:20:20+08:00"}
    log.Info("Something happened.")

    // {"fields":{"num":1},"level":"info","message":"Something happened.","name":"test","time":"2020-02-20T20:20:20+08:00"}
    log.WithField("num", 1).Info("Something happened.")
}

License

Apache-2.0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Entity

type Entity interface {
	// Name returns the logger name.
	Name() string

	// Time returns the log time.
	Time() time.Time

	// TimeString returns the log time string formatted with the default time format.
	TimeString() string

	// Level returns the log level.
	Level() Level

	// Message returns the log message.
	Message() string

	// Fields returns the log fields.
	Fields() map[string]interface{}

	// Context returns the log context.
	Context() context.Context

	// Caller returns the log caller.
	// If it is not enabled, an empty string is always returned.
	Caller() string
}

Entity interface defines the entity of the log.

type Formatter

type Formatter interface {
	// Format formats the given log entity into character data and writes it to
	// the given buffer. If the error returned is not empty, the log will be discarded
	// and the registered log hook will not be triggered. We will output the error
	// information to os.Stderr.
	Format(Entity, *bytes.Buffer) error
}

Formatter interface defines a standard log formatter. The log formatter is not necessary for built-in loggers. We serialize logs to JSON format by default. This interface only provides a simple way to change this default behavior.

type FormatterFunc

type FormatterFunc func(Entity, *bytes.Buffer) error

FormatterFunc type defines a log formatter in the form of a function.

func (FormatterFunc) Format

func (f FormatterFunc) Format(e Entity, b *bytes.Buffer) error

Format formats the given log entity into character data and writes it to the given buffer.

type Hook

type Hook interface {
	// Levels returns the log levels associated with the current log hook.
	// This method is only called once when the log hook is added to the logger.
	// If the returned log levels are empty, the hook will not be added.
	// If there are invalid log level in the returned log levels, it will be automatically ignored.
	Levels() []Level

	// Fire receives the summary of the log and performs the full logic of the log hook.
	// This method is called in parallel, and each log is called once.
	// Errors returned by this method are handled by the internal error handler (output to standard
	// error by default), and any errors returned will not prevent log writing.
	// The log summary instance received by this method will be cleaned up and recycled after the
	// log writing is completed. The log hook program should not hold the log summary instance.
	Fire(Summary) error
}

Hook interface defines the log hook program. The log hook is triggered synchronously after the log is successfully formatted and before it is written. Any error returned by the hook program will not prevent the log from being written.

func NewHookFromFunc

func NewHookFromFunc(levels []Level, hook func(Summary) error) Hook

NewHookFromFunc returns a log hook created from a given log level and function.

type HookBag

type HookBag interface {
	Hook

	// Add adds the given log hook to the current hook bag.
	Add(Hook)
}

HookBag interface defines a collection of multiple log hooks.

func NewHookBag

func NewHookBag() HookBag

NewHookBag returns a built-in HookBag instance.

type Level

type Level uint32

Level is the level of the log.

const (
	// PanicLevel indicates a very serious event at the highest level.
	PanicLevel Level = iota + 1

	// FatalLevel indicates that an event occurred that the application
	// cannot continue to run.
	FatalLevel

	// ErrorLevel indicates that an event occurred within the application
	// but does not affect continued operation.
	ErrorLevel

	// WarnLevel indicates that a noteworthy event has occurred inside
	// the application.
	WarnLevel

	// InfoLevel represents some general information events.
	InfoLevel

	// DebugLevel represents some informational events for debugging, and
	// very verbose logging.
	DebugLevel

	// TraceLevel represents the finest granular information event.
	TraceLevel
)

func GetAllLevels

func GetAllLevels() []Level

GetAllLevels returns all supported log levels.

func MustParseLevel

func MustParseLevel(s string) Level

MustParseLevel parses the log level from the given string. If the given string is invalid, it will panic.

func ParseLevel

func ParseLevel(s string) (Level, error)

ParseLevel parses the log level from the given string.

func (Level) CapitalString

func (level Level) CapitalString() string

CapitalString returns the capital string form of the current level. If the log level is not supported, always returns "UNKNOWN".

func (Level) IsEnabled

func (level Level) IsEnabled(l Level) bool

IsEnabled returns whether the given level is included in the current level.

func (Level) IsValid

func (level Level) IsValid() bool

IsValid determines whether the current level is valid.

func (Level) ShortCapitalString

func (level Level) ShortCapitalString() string

ShortCapitalString returns the short capital string form of the current level. If the log level is not supported, always returns "UNO".

func (Level) ShortString

func (level Level) ShortString() string

ShortString returns the short string form of the current level. If the log level is not supported, always returns "uno".

func (Level) String

func (level Level) String() string

String returns the string form of the current level. If the log level is not supported, always returns "unknown".

type Log

type Log interface {
	// Name returns the logger name.
	Name() string

	// WithField adds the given extended data to the log.
	WithField(string, interface{}) Log

	// WithError adds the given error to the log.
	// This method is relative to WithField("error", error).
	WithError(error) Log

	// WithFields adds the given multiple extended data to the log.
	WithFields(map[string]interface{}) Log

	// WithContext adds the given context to the log.
	WithContext(context.Context) Log

	// WithCaller forces the caller report of the current log to be enabled.
	WithCaller(...int) Log

	// Log uses the given parameters to record a log of the specified level.
	// If the given log level is PanicLevel, the given panic function will be
	// called automatically after logging is completed.
	// If the given log level is FatalLevel, the given exit function will be
	// called automatically after logging is completed.
	// If the given log level is invalid, the log will be discarded.
	Log(Level, ...interface{})

	// Logln uses the given parameters to record a log of the specified level.
	// If the given log level is PanicLevel, the given panic function will be
	// called automatically after logging is completed.
	// If the given log level is FatalLevel, the given exit function will be
	// called automatically after logging is completed.
	// If the given log level is invalid, the log will be discarded.
	Logln(Level, ...interface{})

	// Logf uses the given parameters to record a log of the specified level.
	// If the given log level is PanicLevel, the given panic function will be
	// called automatically after logging is completed.
	// If the given log level is FatalLevel, the given exit function will be
	// called automatically after logging is completed.
	// If the given log level is invalid, the log will be discarded.
	Logf(Level, string, ...interface{})

	// Trace uses the given parameters to record a TraceLevel log.
	Trace(...interface{})

	// Traceln uses the given parameters to record a TraceLevel log.
	Traceln(...interface{})

	// Tracef uses the given parameters to record a TraceLevel log.
	Tracef(string, ...interface{})

	// Print uses the given parameters to record a TraceLevel log.
	Print(...interface{})

	// Println uses the given parameters to record a TraceLevel log.
	Println(...interface{})

	// Printf uses the given parameters to record a TraceLevel log.
	Printf(string, ...interface{})

	// Debug uses the given parameters to record a DebugLevel log.
	Debug(...interface{})

	// Debugln uses the given parameters to record a DebugLevel log.
	Debugln(...interface{})

	// Debugf uses the given parameters to record a DebugLevel log.
	Debugf(string, ...interface{})

	// Info uses the given parameters to record a InfoLevel log.
	Info(...interface{})

	// Infoln uses the given parameters to record a InfoLevel log.
	Infoln(...interface{})

	// Infof uses the given parameters to record a InfoLevel log.
	Infof(string, ...interface{})

	// Echo uses the given parameters to record a InfoLevel log.
	Echo(...interface{})

	// Echoln uses the given parameters to record a InfoLevel log.
	Echoln(...interface{})

	// Echof uses the given parameters to record a InfoLevel log.
	Echof(string, ...interface{})

	// Warn uses the given parameters to record a WarnLevel log.
	Warn(...interface{})

	// Warnln uses the given parameters to record a WarnLevel log.
	Warnln(...interface{})

	// Warnf uses the given parameters to record a WarnLevel log.
	Warnf(string, ...interface{})

	// Warning uses the given parameters to record a WarnLevel log.
	Warning(...interface{})

	// Warningln uses the given parameters to record a WarnLevel log.
	Warningln(...interface{})

	// Warningln uses the given parameters to record a WarnLevel log.
	Warningf(string, ...interface{})

	// Error uses the given parameters to record a ErrorLevel log.
	Error(...interface{})

	// Errorln uses the given parameters to record a ErrorLevel log.
	Errorln(...interface{})

	// Errorf uses the given parameters to record a ErrorLevel log.
	Errorf(string, ...interface{})

	// Fatal uses the given parameters to record a FatalLevel log.
	// After the log record is completed, the system will automatically call
	// the exit function given in advance.
	Fatal(...interface{})

	// Fatalln uses the given parameters to record a FatalLevel log.
	// After the log record is completed, the system will automatically call
	// the exit function given in advance.
	Fatalln(...interface{})

	// Fatalf uses the given parameters to record a FatalLevel log.
	// After the log record is completed, the system will automatically call
	// the exit function given in advance.
	Fatalf(string, ...interface{})

	// Panic uses the given parameters to record a PanicLevel log.
	// After the log record is completed, the system will automatically call
	// the panic function given in advance.
	Panic(...interface{})

	// Panicln uses the given parameters to record a PanicLevel log.
	// After the log record is completed, the system will automatically call
	// the panic function given in advance.
	Panicln(...interface{})

	// Panicf uses the given parameters to record a PanicLevel log.
	// After the log record is completed, the system will automatically call
	// the panic function given in advance.
	Panicf(string, ...interface{})
}

Log interface defines an extensible log.

type Logger

type Logger interface {
	Log

	// GetLevel returns the current logger level.
	GetLevel() Level

	// SetLevel sets the current logger level.
	SetLevel(Level) Logger

	// SetOutput sets the current logger output writer.
	// If the given writer is nil, os.Stdout is used.
	SetOutput(io.Writer) Logger

	// SetLevelOutput sets the current logger level output writer.
	// The level output writer is used to write log data of a given level.
	// If the given writer is nil, the level writer will be disabled.
	SetLevelOutput(level Level, w io.Writer) Logger

	// SetNowFunc sets the function that gets the current time.
	// If the given function is nil, time.Now is used.
	SetNowFunc(func() time.Time) Logger

	// SetExitFunc sets the exit function of the current logger.
	// If the given function is nil, the exit function is disabled.
	// The exit function is called automatically after the FatalLevel level log is recorded.
	// By default, the exit function we use is os.Exit.
	SetExitFunc(func(int)) Logger

	// SetPanicFunc sets the panic function of the current logger.
	// If the given function is nil, the panic function is disabled.
	// The panic function is called automatically after the PanicLevel level log is recorded.
	// By default, the panic function we use is func(s string) { panic(s) }.
	SetPanicFunc(func(string)) Logger

	// SetFormatter sets the log formatter for the current logger.
	// If the given log formatter is nil, we will record the log in JSON format.
	SetFormatter(Formatter) Logger

	// SetDefaultTimeFormat sets the default log time format for the current logger.
	// If the given time format is empty string, internal.DefaultTimeFormat is used.
	SetDefaultTimeFormat(string) Logger

	// EnableCaller enables caller reporting on all levels of logs.
	EnableCaller(...int) Logger

	// EnableCaller enables caller reporting on logs of a given level.
	EnableLevelCaller(Level, ...int) Logger

	// AddHook adds the given log hook to the current logger.
	AddHook(Hook) Logger

	// AddHookFunc adds the given log hook function to the current logger.
	AddHookFunc([]Level, func(Summary) error) Logger
}

Logger interface defines a standard logger.

func New

func New(name string) Logger

New creates a new Logger instance. By default, the logger level is TraceLevel and logs will be output to os.Stdout.

type Summary

type Summary interface {
	Entity
	io.Reader

	// Bytes returns the log content bytes.
	// This method returns the content processed by the formatter.
	Bytes() []byte

	// String returns the log content string.
	// This method returns the content processed by the formatter.
	String() string

	// Size returns the log content size.
	Size() int
}

Summary interface defines the summary of the log. The log summary is the final state of a log, and the content of the log will no longer change.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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