logger

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: May 15, 2023 License: Apache-2.0 Imports: 15 Imported by: 1

README

ZKits Logger Library

Golang Version Mentioned in Awesome Go Build Status Build status Coverage Status Codacy Badge Go Report Card

About

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

  • Does not depend on any third-party libraries.
  • Provides controllable caller and stack information reporting.
  • Provides 7 log level support.
  • Compatible with standard library logger *log.Logger.
  • Support chain calls and add multiple log extension data.
  • Provides logging hook support.
  • Built-in multiple log formatters, support custom log formatters.
  • Support log output to different writers by level.
  • Supports output interceptor to easily hijack and control log output.
  • Provides a log file writer that supports log file rotation by size.

According to the plan, this library will release 2 versions every year. If there are new security issues or PRs, we will release new versions according to the actual situation.

Example image uses the ConsoleFormatter and disables the exit and panic functions. For the default Logger instance, we use the JSONFormatter.

Install

   go get -u -v github.com/edoger/zkits-logger

Quick Start

    import "github.com/edoger/zkits-logger"

    // Creates a logger instance with the specified name.
    // Empty name are allowed.
    log := logger.New("app")
    // {"level":"info","message":"Hello.","name":"app","time":"2020-02-20T20:20:20+08:00"}
    log.Info("Hello.")
    // {"fields":{"field":1},"level":"info","message":"Hello.","name":"app","time":"2020-02-20T20:20:20+08:00"}
    log.WithField("field", 1).Info("Hello.")

Design Concept

Zero Dependencies

We think the logger should be lightweight enough, because the applications we develop are already complex enough, they often have massive third-party dependencies, so let's not add additional dependencies to the application, which is why I built this library one of the reasons.

No Locker

For the performance of the logger, we adopt a lock-free design as a whole. Therefore, we agree that the shared data of the logger is read-only, and we require the application to not modify its internal shared data after initializing the logger. (formatters, log writers, hooks, etc).

For the logger level, it can be modified at runtime, as it is a common and meaningful operation for applications to adjust the level of the logger at runtime.

We recommend initializing the logger (Logger) as soon as it is created (if required by the application), using the logging interface Logger.AsLog() to provide logging functionality.

    package log
    
    import "github.com/edoger/zkits-logger"
    
    var defaultLogger = logger.New("name")

    // Initialize the logger.
    func Initialize(/* Your config */) {
        // defaultLogger.SetLevel(Level)
        // defaultLogger.SetOutput(Writer)
        // defaultLogger.SetFormatter(Formatter)
        // ... ...
    }

    // GetLogger gets the default logger instance.
    func GetLogger() logger.Log {
        // Mask the setting method of Logger.
        return defaultLogger.AsLog()
    }
Chained Calls & Log Tree

Chained calls are more in line with the way we think when writing source code (left-to-right, continuous). We have designed a number of Log.With* methods to extend the additional fields of the log, and through these methods, more field information can be recorded. At the same time, these methods will create and return new log objects, we can use this feature to add differentiated fields to different modules.

    // Create Log instance with additional properties.
    // All SubLog inherit the properties of the BaseLog (properties with the same name will be overwritten), 
    // and they are independent of each other and no longer associated with the BaseLog.
    SubLog1 := BaseLog.WithField("key", value)
    SubLog2 := BaseLog.WithFields(map[string]interface{}{/* multiple fields */})
    SubLog3 := BaseLog.WithContext(ctx)
    // Field key-value pairs are also supported.
    SubLog4 := BaseLog.WithFieldPairs("key1", value1, "key2", value2, /* More ... */)
    /* More ... */

    // Add a logger for the submodule, the logs recorded by the submodule all have
    // the additional properties we added.
    SubModule.WithLogger(Log.WithField("module", "ModuleName"))

Best practices:

    // Good
    Log.WithFields(map[string]interface{}{"field1": var1, "field2": var2})
    // Bad
    Log.WithField("field1", var1).WithField("field2", var2)

The application is not a modular design? No additional properties?

    // Add a fixed prefix to log messages.
    log := Log.WithMessagePrefix("Prefix: ")

    log.Info("Step 1 is done!") // Log message: "Prefix: Step 1 is done!"
    log.Info("Step 2 is done!") // Log message: "Prefix: Step 2 is done!"

Need to determine if a log level is visible before logging?

    if Log.IsLevelEnabled(Level) { /* Print log */ }
    // or
    if Log.IsDebugLevelEnabled() { /* Print debug log */ }
Quickly Locate Bugs

The purpose of the log is to observe the running status of our application. When there is a problem with the application, the log can help us quickly find and solve the root cause of the problem. We've designed our logger with this in mind, and for this reason we provide a very flexible and concise "scenario" grabbing capability.

Log error:

    // Tell us the file name and line number when logging the error.
    Log.WithCaller().WithError(err).Error("Task failed!") // Log errors into separate field.
    Log.WithCaller().Errorf("Task failed: %s.", err)

    // Too troublesome? Code too verbose? Then we set it globally!
    // Callers are now automatically added to all logs that meet the level.
    Logger.EnableLevelCaller(ErrorLevel)
    Logger.EnableLevelsCaller([]Level{ErrorLevel, FatalLevel, PanicLevel})

Panic:

    // Tell us the crash call stack information.
    Log.WithStack().Error("Application crash!")

    // Setting Logger.SetExitFunc(nil) disables the automatic call os.Exit. 
    Log.WithStack().Fatal("Application crash!")
    // Setting Logger.SetPanicFunc(nil) disables the automatic call panic. 
    Log.WithStack().Panic("Application crash!")

Future Overview

Log Hooks

Log hooks allow us to do some extra things before logging. Log hooks are designed to uniformly handle log events (by Level) that we are interested in. Log hooks should be lightweight enough, such as: counting the number of logs, triggering alarms, etc.

    // Define the hook for our application.
    type AppHook struct {}

    func (*AppHook) Levels() []Level {
        return []Level{ErrorLevel, FatalLevel, PanicLevel}
    }

    func (*AppHook) Fire(s Summary) error {
        // Do something!
        return nil
    }

    // Register application log hook.
    Logger.AddHook(new(AppHook))

Don't want to define hook struct?

    Logger.AddHookFunc([]Level{ErrorLevel}, func(s Summary) error {
        // Do something!
        return nil
    })

Do we have multiple hooks that need to be registered?

    // Create a hook collection.
    bag := NewHookBag()

    // Add our hooks.
    bag.Add(Hook1)
    bag.Add(Hook2)
    /* ... More ... */
    bag.Add(HookN)

    // Register them all at once.
    Logger.AddHook(bag)

HookBag also needs to adhere to our "No Locker" philosophy, do not continue to add hooks after registration.

Log Formatter

The log formatter is used to format the log object into string data as expected. The log formatter should be as efficient as possible, this is the most CPU-intensive component of the logger.

We have built in several common formatters, they may not be the best and most suitable, but they are rigorously tested and work out of the box.

JSON Formatter

    // The default formatter, if you don't change it, that's it.
    f := DefaultJSONFormatter()

    // Create one and configure custom field names.
    // If the full parameter is true, it will always ensure that all fields exist in the top-level json object.
    f, err := NewJSONFormatter(keys map[string]string, full bool)
    f := MustNewJSONFormatter(keys map[string]string, full bool)

Custom JSON field names will not benefit from the optimizations of the JSON serializer.

Text Formatter

    f := DefaultTextFormatter()
    f := DefaultQuoteTextFormatter() // Escape invisible characters.

    // The format parameter is used to control the format of the log, and it has many control parameters.
    // For example:
    //     "[{name}][{time}][{level}] {caller} {message} {fields}"
    // The supported placeholders are:
    //     {name}      The name of the logger that recorded this log.
    //     {time}      Record the time of this log.
    //     {level}     The level of this log.
    //     {caller}    The name and line number of the file where this log was generated. (If enabled)
    //     {message}   The message of this log.
    //     {fields}    The extended fields of this log. (if it exists)
    //     {stack}     The call stack of this log. (if it exists)
    // It is worth knowing:
    //     1. For the {time} parameter, we can specify time format, like this: {time@2006-01-02 15:04:05}.
    //     2. For the {level} parameter, we can specify level format, like this: {level@sc},
    //        {level@sc} or {level@cs} will call the Level.ShortCapitalString method.
    //        {level@s} will call the Level.ShortString method.
    //        {level@c} will call the Level.CapitalString method.
    //        For other will call the Level.String method.
    //     3. Considering the aesthetics of the format, for {caller} and {fields} and {stack}, if
    //        there is non-empty data, a space will be automatically added in front.
    //        If this behavior is not needed, use {caller@?} or {fields@?} or {stack@?} parameters.
    // The quote parameter is used to escape invisible characters in the log.
    f, err := NewTextFormatter(format string, quote bool)
    f := MustNewTextFormatter(format string, quote bool)

Console Formatter

    // The console formatter is very similar to the text formatter. The only difference is that
    // we output different console colors for different log levels, which is very useful when
    // outputting logs from the console.
    f := NewConsoleFormatter()
Output Interceptor

The output interceptor can bypass the output writer of the logger binding (Logger.SetOutput or Logger.SetLevelOutput or Logger.SetLevelsOutput) and output the log to our custom system (these systems are often dynamic or cannot be wrapped as io.Writer).

    // The io.Writer in the interceptor parameter is the io.Writer instance bound by the logger.
    Logger.SetOutputInterceptor(func(s Summary, w io.Writer) (int, error) {
        // Do something!
        return s.Size(), nil
    })

Once the output interceptor is enabled, we will no longer write logs to the log writer, even if the interceptor returns an error.

Format Output

The FormatOutput allows customizing the format and writer of each log.

    // The io.Writer in the interceptor parameter is the io.Writer instance bound by the logger.
    Logger.SetFormatOutput(FormatOutputFunc(func(e Entity, b *bytes.Buffer) (io.Writer, error) {
        // 1. Format the log and write to the buffer.
		// 2. Determines and returns the writer to which the log needs to be written.
		return os.Stdout, nil
    })

After setting FormatOutput, the original log formatter will not be used, and when FormatOutput returns the writer is not nil, the original writer will not be used either.

Log Context & Trace

The log context is to support the trace technology. By default, we will not do any operations on the context object bound to the log. If you need to use the link tracking technology, you should define a custom log formatter to process the trace data.

    // Bind the context for the log.
    Log.WithContext(ctx)

    // Register a formatter that supports parsing trace data.
    Logger.SetFormatter(FormatterFunc(func(e Entity, b *bytes.Buffer) error {
        ctx := e.Context()
        // 1. Parse trace data from Context.
        // 2. Formats the log Entity and writes the data to the Buffer.
        return nil
    }))

Parsing trace data is difficult to standardize, and solutions used by different applications are completely different, so we leave this function to users to implement.

⚠️ The custom log formatter needs to append a newline after the formatted log data is written into the buffer, otherwise the log will not wrap automatically.

Log Bridge

Log bridge is a concept here. Applications often have many third-party libraries and components. In order to adapt to the log loggers of these libraries and components, we built some log bridges without introducing dependencies. They are responsible for converting our loggers to loggers for these libraries and components.

Standard Library Logger

    import log // Standard log package

    // Convert our logger to the standard library logger instance.
    g := Logger.AsStandardLogger() // Return *log.Logger instance.

    // You can also customize the default log level.
    log.New(NewLevelWriter(DebugLevel, Logger.AsLog()))

💣 The *log.Logger automatically exits the system and panics when logging fatal and panic level log.

License

Apache-2.0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsHighPriorityLevel added in v1.5.1

func IsHighPriorityLevel(level Level) bool

IsHighPriorityLevel determines whether the given level is a high priority level.

func IsLowPriorityLevel added in v1.5.1

func IsLowPriorityLevel(level Level) bool

IsLowPriorityLevel determines whether the given level is a low priority level.

func MustNewFileWriter added in v1.4.2

func MustNewFileWriter(name string, max, backup uint32) io.WriteCloser

MustNewFileWriter is like NewFileWriter, but triggers a panic when an error occurs.

func NewFileWriter added in v1.4.2

func NewFileWriter(name string, max, backup uint32) (io.WriteCloser, error)

NewFileWriter creates and returns an io.WriteCloser instance from the given path. The max parameter is used to limit the maximum size of the log file, if it is 0, the file size limit will be disabled. The log files that exceed the maximum size limit will be renamed. The backup parameter can limit the maximum number of backup log files retained. The log file writer we returned does not restrict concurrent writing. If necessary, you can use the writer wrapper with lock provided by us.

func NewLevelWriter added in v1.4.6

func NewLevelWriter(l Level, g Log) io.Writer

NewLevelWriter creates a writer that records each message written as a log message. Generally, this writer is used to bridge the loggers of the standard library.

func NewMultiWriter added in v1.4.4

func NewMultiWriter(writers ...io.Writer) io.Writer

NewMultiWriter creates a writer that duplicates its writes to all the provided writers. If any writer fails to write, it will continue to try to write to other writers. If you need to interrupt writing when any writer fails to write, please use io.MultiWriter.

func NewMutexWriter added in v1.4.5

func NewMutexWriter(w io.Writer) io.Writer

NewMutexWriter creates and returns a mutex writer. Mutually exclusive writers ensure mutual exclusion of individual write calls.

func NewMutexWriterWithLocker added in v1.4.8

func NewMutexWriterWithLocker(w io.Writer, mu sync.Locker) io.Writer

NewMutexWriterWithLocker creates and returns a mutex writer from the given locker.

Types

type Entity added in v1.1.0

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

	// HasFields determines whether the log contains fields.
	HasFields() bool

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

	// HasContext determines whether the log contains a context.
	HasContext() bool

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

	// HasCaller determines whether the log contains caller information.
	HasCaller() bool

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

	// HasStack determines whether the log contains call stack information.
	HasStack() bool

	// Stack returns the call stack information at the logging location.
	// Returns nil if not enabled.
	Stack() []string

	// Buffer returns the entity buffer instance.
	Buffer() *bytes.Buffer
}

Entity interface defines the entity of the log.

type FormatOutput added in v1.5.1

type FormatOutput interface {
	// Format formats the given log entity and returns the writer to which the log needs to be written.
	// 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.
	// If the returned log writer is nil, the default log writer is used.
	Format(e Entity, b *bytes.Buffer) (io.Writer, error)
}

FormatOutput defines the format output of the logger.

func NewFormatOutput added in v1.5.1

func NewFormatOutput(f Formatter, w io.Writer) FormatOutput

NewFormatOutput creates a log format output instance from the given formatter and writer.

func NewLevelPriorityFormatOutput added in v1.5.1

func NewLevelPriorityFormatOutput(high, low FormatOutput) FormatOutput

NewLevelPriorityFormatOutput creates a log level priority format output instance from the given parameters.

type FormatOutputFunc added in v1.5.1

type FormatOutputFunc func(e Entity, b *bytes.Buffer) (io.Writer, error)

FormatOutputFunc type defines a log format output in the form of a function.

func (FormatOutputFunc) Format added in v1.5.1

func (f FormatOutputFunc) Format(e Entity, b *bytes.Buffer) (io.Writer, error)

Format formats the given log entity and returns the writer to which the log needs to be written.

type Formatter added in v1.1.0

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.

func DefaultJSONFormatter added in v1.4.0

func DefaultJSONFormatter() Formatter

DefaultJSONFormatter returns the default json formatter.

func DefaultQuoteTextFormatter added in v1.4.2

func DefaultQuoteTextFormatter() Formatter

DefaultQuoteTextFormatter returns the default quote text formatter.

func DefaultTextFormatter added in v1.4.0

func DefaultTextFormatter() Formatter

DefaultTextFormatter returns the default text formatter.

func MustNewJSONFormatter added in v1.4.0

func MustNewJSONFormatter(keys map[string]string, full bool) Formatter

MustNewJSONFormatter is like NewJSONFormatter, but triggers a panic when an error occurs.

func MustNewTextFormatter added in v1.4.0

func MustNewTextFormatter(format string, quote bool) Formatter

MustNewTextFormatter is like NewTextFormatter, but triggers a panic when an error occurs.

func NewConsoleFormatter added in v1.4.4

func NewConsoleFormatter() Formatter

NewConsoleFormatter creates and returns an instance of the log console formatter. The console formatter is very similar to the text formatter. The only difference is that we output different console colors for different log levels, which is very useful when outputting logs from the console.

func NewJSONFormatter added in v1.4.0

func NewJSONFormatter(keys map[string]string, full bool) (Formatter, error)

NewJSONFormatter creates and returns an instance of the log json formatter. The keys parameter is used to modify the default json field name. If the full parameter is true, it will always ensure that all fields exist in the top-level json object.

func NewJSONFormatterFromPool added in v1.4.7

func NewJSONFormatterFromPool(p JSONFormatterObjectPool) Formatter

NewJSONFormatterFromPool creates a JSON formatter from the given JSON serializable object pool.

func NewTextFormatter added in v1.4.0

func NewTextFormatter(format string, quote bool) (Formatter, error)

NewTextFormatter creates and returns an instance of the log text formatter. The format parameter is used to control the format of the log, and it has many control parameters. For example:

"[{name}][{time}][{level}] {caller} {message} {fields}"

The supported placeholders are:

{name}      The name of the logger that recorded this log.
{time}      Record the time of this log.
{level}     The level of this log.
{caller}    The name and line number of the file where this log was generated. (If enabled)
{message}   The message of this log.
{fields}    The extended fields of this log. (if it exists)
{stack}     The call stack of this log. (if it exists)

It is worth knowing:

  1. For the {time} parameter, we can specify time format, like this: {time@2006-01-02 15:04:05}.
  2. For the {level} parameter, we can specify level format, like this: {level@sc}, {level@sc} or {level@cs} will call the Level.ShortCapitalString method. {level@s} will call the Level.ShortString method. {level@c} will call the Level.CapitalString method. For other will call the Level.String method.
  3. Considering the aesthetics of the format, for {caller} and {fields} and {stack}, if there is non-empty data, a space will be automatically added in front. If this behavior is not needed, use {caller@?} or {fields@?} or {stack@?} parameters.

The quote parameter is used to escape invisible characters in the log.

type FormatterFunc added in v1.1.0

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

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

func (FormatterFunc) Format added in v1.1.0

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 added in v1.1.0

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

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

type HookBag added in v1.1.0

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 added in v1.1.0

func NewHookBag() HookBag

NewHookBag returns a built-in HookBag instance.

type JSONFormatterObjectPool added in v1.4.7

type JSONFormatterObjectPool interface {
	// GetObject creates and returns a new JSON log object from the given log Entity.
	// The returned object must be JSON-Serializable, otherwise the formatter will fail to work.
	GetObject(Entity) interface{}

	// PutObject recycles json serialized objects.
	// This method must clean up the log data bound to the object to free memory.
	PutObject(interface{})
}

JSONFormatterObjectPool defines a pool of serializable objects for JSON formatter. This object pool is used to create and recycle json log objects.

type Level

type Level uint32

Level is the level of the log. The zero Level value is an invalid log level.

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 added in v1.1.0

func GetAllLevels() []Level

GetAllLevels returns all supported log levels.

func GetHighPriorityLevels added in v1.4.9

func GetHighPriorityLevels() []Level

GetHighPriorityLevels returns all supported high priority log levels.

func GetLowPriorityLevels added in v1.4.9

func GetLowPriorityLevels() []Level

GetLowPriorityLevels returns all supported low priority 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 added in v1.3.0

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) ColorfulCapitalString added in v1.4.6

func (level Level) ColorfulCapitalString() string

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

func (Level) ColorfulShortCapitalString added in v1.4.6

func (level Level) ColorfulShortCapitalString() string

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

func (Level) ColorfulShortString added in v1.4.6

func (level Level) ColorfulShortString() string

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

func (Level) ColorfulString added in v1.4.6

func (level Level) ColorfulString() string

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

func (Level) IsEnabled added in v1.1.0

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 added in v1.3.0

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 added in v1.3.0

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

	// WithMessagePrefix adds a fixed message prefix to the current log.
	WithMessagePrefix(string) Log

	// 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

	// WithFieldPairs adds the given key-value pairs to the log.
	WithFieldPairs(pairs ...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

	// WithStack adds call stack information to the current log.
	WithStack() Log

	// IsLevelEnabled checks whether the given log level is enabled.
	// Always returns false if the given log level is invalid.
	IsLevelEnabled(Level) bool

	// IsPanicLevelEnabled checks whether the PanicLevel is enabled.
	IsPanicLevelEnabled() bool

	// IsFatalLevelEnabled checks whether the FatalLevel is enabled.
	IsFatalLevelEnabled() bool

	// IsErrorLevelEnabled checks whether the ErrorLevel is enabled.
	IsErrorLevelEnabled() bool

	// IsWarnLevelEnabled checks whether the WarnLevel is enabled.
	IsWarnLevelEnabled() bool

	// IsInfoLevelEnabled checks whether the InfoLevel is enabled.
	IsInfoLevelEnabled() bool

	// IsDebugLevelEnabled checks whether the DebugLevel is enabled.
	IsDebugLevelEnabled() bool

	// IsTraceLevelEnabled checks whether the TraceLevel is enabled.
	IsTraceLevelEnabled() bool

	// 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{})

	// Warningf 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.
	// When the given log level is invalid, this method does nothing.
	SetLevel(Level) Logger

	// SetLevelString sets the current logger level by string.
	SetLevelString(s string) error

	// ForceSetLevelString sets the current logger level by string.
	// When the given log level string is invalid, this method does nothing.
	ForceSetLevelString(s string) 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, io.Writer) Logger

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

	// SetOutputInterceptor sets the output interceptor for the current logger.
	// If the given interceptor is nil, the log data is written to the output writer.
	SetOutputInterceptor(func(Summary, io.Writer) (int, error)) 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

	// SetFormatOutput sets the log format output.
	// After setting the format output, the format and output of the logger will be controlled by this structure,
	// and the bound log output and log level output will no longer be used.
	// If format output needs to be disabled, set to nil and the logger will back to the original behavior.
	SetFormatOutput(FormatOutput) 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

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

	// EnableLevelsCaller enables caller reporting on logs of the given levels.
	EnableLevelsCaller([]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

	// EnableHook enables or disables the log hook.
	EnableHook(bool) Logger

	// AsLog converts current Logger to Log instances, which is unidirectional.
	AsLog() Log

	// AsStandardLogger converts the current logger to a standard library logger instance.
	AsStandardLogger() *stdlog.Logger

	// SetStackPrefixFilter sets the call stack prefix filter rules.
	SetStackPrefixFilter(...string) 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

	// Clone returns a copy of the current log summary (excluding context).
	Clone() Summary

	// CloneWithContext returns a copy of the current log summary and sets its context to the given value.
	CloneWithContext(context.Context) Summary
}

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.

type UnimplementedFormatter added in v1.5.0

type UnimplementedFormatter struct{}

UnimplementedFormatter defines an empty, unimplemented log formatter. This is usually used to bypass log formatting and implement custom loggers with interceptors.

func (*UnimplementedFormatter) Format added in v1.5.0

Format does nothing here and always returns a nil error.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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