package
1.4.3
Repository: https://github.com/hduhelp/go-zero.git
Documentation: pkg.go.dev

# README

logx

English | 简体中文

logx configurations

type LogConf struct {
	ServiceName         string              `json:",optional"`
	Mode                string              `json:",default=console,options=[console,file,volume]"`
	Encoding            string              `json:",default=json,options=[json,plain]"`
	TimeFormat          string              `json:",optional"`
	Path                string              `json:",default=logs"`
	Level               string              `json:",default=info,options=[info,error,severe]"`
	Compress            bool                `json:",optional"`
	KeepDays            int                 `json:",optional"`
	StackCooldownMillis int                 `json:",default=100"`
	MaxBackups          int                 `json:",default=0"`
	MaxSize             int                 `json:",default=0"`
	Rotation            string              `json:",default=daily,options=[daily,size]"`
}
  • ServiceName: set the service name, optional. on volume mode, the name is used to generate the log files. Within rest/zrpc services, the name will be set to the name of rest or zrpc automatically.
  • Mode: the mode to output the logs, default is console.
    • console mode writes the logs to stdout/stderr.
    • file mode writes the logs to the files specified by Path.
    • volume mode is used in docker, to write logs into mounted volumes.
  • Encoding: indicates how to encode the logs, default is json.
    • json mode writes the logs in json format.
    • plain mode writes the logs with plain text, with terminal color enabled.
  • TimeFormat: customize the time format, optional. Default is 2006-01-02T15:04:05.000Z07:00.
  • Path: set the log path, default to logs.
  • Level: the logging level to filter logs. Default is info.
    • info, all logs are written.
    • error, info logs are suppressed.
    • severe, info and error logs are suppressed, only severe logs are written.
  • Compress: whether or not to compress log files, only works with file mode.
  • KeepDays: how many days that the log files are kept, after the given days, the outdated files will be deleted automatically. It has no effect on console mode.
  • StackCooldownMillis: how many milliseconds to rewrite stacktrace again. It’s used to avoid stacktrace flooding.
  • MaxBackups: represents how many backup log files will be kept. 0 means all files will be kept forever. Only take effect when Rotation is size. NOTE: the level of option KeepDays will be higher. Even thougth MaxBackups sets 0, log files will still be removed if the KeepDays limitation is reached.
  • MaxSize: represents how much space the writing log file takes up. 0 means no limit. The unit is MB. Only take effect when Rotation is size.
  • Rotation: represents the type of log rotation rule. Default is daily.
    • daily rotate the logs by day.
    • size rotate the logs by size of logs.

Logging methods

type Logger interface {
	// Error logs a message at error level.
	Error(...interface{})
	// Errorf logs a message at error level.
	Errorf(string, ...interface{})
	// Errorv logs a message at error level.
	Errorv(interface{})
	// Errorw logs a message at error level.
	Errorw(string, ...LogField)
	// Info logs a message at info level.
	Info(...interface{})
	// Infof logs a message at info level.
	Infof(string, ...interface{})
	// Infov logs a message at info level.
	Infov(interface{})
	// Infow logs a message at info level.
	Infow(string, ...LogField)
	// Slow logs a message at slow level.
	Slow(...interface{})
	// Slowf logs a message at slow level.
	Slowf(string, ...interface{})
	// Slowv logs a message at slow level.
	Slowv(interface{})
	// Sloww logs a message at slow level.
	Sloww(string, ...LogField)
	// WithContext returns a new logger with the given context.
	WithContext(context.Context) Logger
	// WithDuration returns a new logger with the given duration.
	WithDuration(time.Duration) Logger
}
  • Error, Info, Slow: write any kind of messages into logs, with like fmt.Sprint(…).
  • Errorf, Infof, Slowf: write messages with given format into logs.
  • Errorv, Infov, Slowv: write any kind of messages into logs, with json marshalling to encode them.
  • Errorw, Infow, Sloww: write the string message with given key:value fields.
  • WithContext: inject the given ctx into the log messages, typically used to log trace-id and span-id.
  • WithDuration: write elapsed duration into the log messages, with key duration.

Integrating with third-party logging libs

For more libs, please implement and PR to https://github.com/zeromicro/zero-contrib

Write the logs to specific stores

logx defined two interfaces to let you customize logx to write logs into any stores.

  • logx.NewWriter(w io.Writer)
  • logx.SetWriter(writer logx.Writer)

For example, if we want to write the logs into kafka instead of console or files, we can do it like below:

type KafkaWriter struct {
	Pusher *kq.Pusher
}

func NewKafkaWriter(pusher *kq.Pusher) *KafkaWriter {
	return &KafkaWriter{
		Pusher: pusher,
	}
}

func (w *KafkaWriter) Write(p []byte) (n int, err error) {
	// writing log with newlines, trim them.
	if err := w.Pusher.Push(strings.TrimSpace(string(p))); err != nil {
		return 0, err
	}

	return len(p), nil
}

func main() {
	pusher := kq.NewPusher([]string{"localhost:9092"}, "go-zero")
	defer pusher.Close()

	writer := logx.NewWriter(NewKafkaWriter(pusher))
	logx.SetWriter(writer)
  
	// more code
}

Complete code: https://github.com/zeromicro/zero-examples/blob/main/logx/tokafka/main.go

Filtering sensitive fields

If we need to prevent the password fields from logging, we can do it like below:

type (
	Message struct {
		Name     string
		Password string
		Message  string
	}

	SensitiveLogger struct {
		logx.Writer
	}
)

func NewSensitiveLogger(writer logx.Writer) *SensitiveLogger {
	return &SensitiveLogger{
		Writer: writer,
	}
}

func (l *SensitiveLogger) Info(msg interface{}, fields ...logx.LogField) {
	if m, ok := msg.(Message); ok {
		l.Writer.Info(Message{
			Name:     m.Name,
			Password: "******",
			Message:  m.Message,
		}, fields...)
	} else {
		l.Writer.Info(msg, fields...)
	}
}

func main() {
	// setup logx to make sure originalWriter not nil,
	// the injected writer is only for filtering, like a middleware.

	originalWriter := logx.Reset()
	writer := NewSensitiveLogger(originalWriter)
	logx.SetWriter(writer)

	logx.Infov(Message{
		Name:     "foo",
		Password: "shouldNotAppear",
		Message:  "bar",
	})
  
	// more code
}

Complete code: https://github.com/zeromicro/zero-examples/blob/main/logx/filterfields/main.go

More examples

https://github.com/zeromicro/zero-examples/tree/main/logx

Give a Star! ⭐

If you like or are using this project to learn or start your solution, please give it a star. Thanks!

# Functions

AddGlobalFields adds global fields.
Alert alerts v in alert level, and the message is written to error log.
Close closes the logging.
CollectSysLog redirects system log into logx info.
ContextWithFields returns a new context with the given fields.
Debug writes v into access log.
Debugf writes v with format into access log.
Debugv writes v into access log with json content.
Debugw writes msg along with fields into access log.
DefaultRotateRule is a default log rotating rule, currently DailyRotateRule.
Disable disables the logging.
DisableStat disables the stat logs.
Error writes v into error log.
Errorf writes v with format into error log.
ErrorStack writes v along with call stack into error log.
ErrorStackf writes v along with call stack in format into error log.
Errorv writes v into error log with json content.
Errorw writes msg along with fields into error log.
Field returns a LogField for the given key and value.
Info writes v into access log.
Infof writes v with format into access log.
Infov writes v into access log with json content.
Infow writes msg along with fields into access log.
Must checks if err is nil, otherwise logs the error and exits.
MustSetup sets up logging with given config c.
NewLessLogger returns a LessLogger.
NewLogger returns a RotateLogger with given filename and rule, etc.
NewSizeLimitRotateRule returns the rotation rule with size limit.
NewWriter creates a new Writer with the given io.Writer.
Reset clears the writer and resets the log level.
SetLevel sets the logging level.
SetUp sets up the logx.
SetWriter sets the logging writer.
Severe writes v into severe log.
Severef writes v with format into severe log.
Slow writes v into slow log.
Slowf writes v with format into slow log.
Slowv writes v into slow log with json content.
Sloww writes msg along with fields into slow log.
Stat writes v into stat log.
Statf writes v with format into stat log.
WithCallerSkip returns a Logger with given caller skip.
WithColor is a helper function to add color to a string, only in plain encoding.
WithColorPadding is a helper function to add color to a string with leading and trailing spaces, only in plain encoding.
WithContext sets ctx to log, for keeping tracing information.
WithCooldownMillis customizes logging on writing call stack interval.
WithDuration returns a Logger with given duration.
WithFields returns a new logger with the given fields.
WithGzip customizes logging to automatically gzip the log files.
WithKeepDays customizes logging to keep logs with days.
WithMaxBackups customizes how many log files backups will be kept.
WithMaxSize customizes how much space the writing log file can take up.
WithRotation customizes which log rotation rule to use.

# Constants

DebugLevel logs everything.
ErrorLevel includes errors, slows, stacks.
InfoLevel does not include debugs.
SevereLevel only log severe messages.

# Variables

ErrLogFileClosed is an error that indicates the log file is already closed.
ErrLogPathNotSet is an error that indicates the log path is not set.
ErrLogServiceNameNotSet is an error that indicates that the service name is not set.

# Structs

No description provided by the author
A LessLogger is a logger that control to log once during the given duration.
A LogConf is a logging config.
No description provided by the author
No description provided by the author
No description provided by the author

# Interfaces

A Logger represents a logger.
No description provided by the author
No description provided by the author

# Type aliases

No description provided by the author