github.com/lingyao2333/mo-zero@v1.4.1/core/logx/readme.md (about)

     1  <img align="right" width="150px" src="https://raw.githubusercontent.com/zeromicro/zero-doc/main/doc/images/go-zero.png">
     2  
     3  # logx
     4  
     5  English | [简体中文](readme-cn.md)
     6  
     7  ## logx configurations
     8  
     9  ```go
    10  type LogConf struct {
    11  	ServiceName         string              `json:",optional"`
    12  	Mode                string              `json:",default=console,options=[console,file,volume]"`
    13  	Encoding            string              `json:",default=json,options=[json,plain]"`
    14  	TimeFormat          string              `json:",optional"`
    15  	Path                string              `json:",default=logs"`
    16  	Level               string              `json:",default=info,options=[info,error,severe]"`
    17  	Compress            bool                `json:",optional"`
    18  	KeepDays            int                 `json:",optional"`
    19  	StackCooldownMillis int                 `json:",default=100"`
    20  	MaxBackups          int                 `json:",default=0"`
    21  	MaxSize             int                 `json:",default=0"`
    22  	Rotation            string              `json:",default=daily,options=[daily,size]"`
    23  }
    24  ```
    25  
    26  - `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.
    27  - `Mode`: the mode to output the logs, default is `console`.
    28    -  `console` mode writes the logs to `stdout/stderr`.
    29    - `file` mode writes the logs to the files specified by `Path`.
    30    - `volume` mode is used in docker, to write logs into mounted volumes.
    31  - `Encoding`: indicates how to encode the logs, default is `json`.
    32    - `json` mode writes the logs in json format.
    33    - `plain` mode writes the logs with plain text, with terminal color enabled.
    34  - `TimeFormat`: customize the time format, optional. Default is `2006-01-02T15:04:05.000Z07:00`.
    35  - `Path`: set the log path, default to `logs`.
    36  - `Level`: the logging level to filter logs. Default is `info`.
    37    - `info`, all logs are written.
    38    - `error`, `info` logs are suppressed.
    39    - `severe`, `info` and `error` logs are suppressed, only `severe` logs are written.
    40  - `Compress`: whether or not to compress log files, only works with `file` mode.
    41  - `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.
    42  - `StackCooldownMillis`: how many milliseconds to rewrite stacktrace again. It’s used to avoid stacktrace flooding.
    43  - `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.
    44  - `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`.
    45  - `Rotation`: represents the type of log rotation rule. Default is `daily`.
    46    - `daily` rotate the logs by day.
    47    - `size` rotate the logs by size of logs.
    48  
    49  ## Logging methods
    50  
    51  ```go
    52  type Logger interface {
    53  	// Error logs a message at error level.
    54  	Error(...interface{})
    55  	// Errorf logs a message at error level.
    56  	Errorf(string, ...interface{})
    57  	// Errorv logs a message at error level.
    58  	Errorv(interface{})
    59  	// Errorw logs a message at error level.
    60  	Errorw(string, ...LogField)
    61  	// Info logs a message at info level.
    62  	Info(...interface{})
    63  	// Infof logs a message at info level.
    64  	Infof(string, ...interface{})
    65  	// Infov logs a message at info level.
    66  	Infov(interface{})
    67  	// Infow logs a message at info level.
    68  	Infow(string, ...LogField)
    69  	// Slow logs a message at slow level.
    70  	Slow(...interface{})
    71  	// Slowf logs a message at slow level.
    72  	Slowf(string, ...interface{})
    73  	// Slowv logs a message at slow level.
    74  	Slowv(interface{})
    75  	// Sloww logs a message at slow level.
    76  	Sloww(string, ...LogField)
    77  	// WithContext returns a new logger with the given context.
    78  	WithContext(context.Context) Logger
    79  	// WithDuration returns a new logger with the given duration.
    80  	WithDuration(time.Duration) Logger
    81  }
    82  ```
    83  
    84  - `Error`, `Info`, `Slow`: write any kind of messages into logs, with like `fmt.Sprint(…)`.
    85  - `Errorf`, `Infof`, `Slowf`: write messages with given format into logs.
    86  - `Errorv`, `Infov`, `Slowv`: write any kind of messages into logs, with json marshalling to encode them.
    87  - `Errorw`, `Infow`, `Sloww`: write the string message with given `key:value` fields.
    88  - `WithContext`: inject the given ctx into the log messages, typically used to log `trace-id` and `span-id`.
    89  - `WithDuration`: write elapsed duration into the log messages, with key `duration`.
    90  
    91  ## Integrating with third-party logging libs
    92  
    93  - zap
    94    - implementation: [https://github.com/zeromicro/zero-contrib/blob/main/logx/zapx/zap.go](https://github.com/zeromicro/zero-contrib/blob/main/logx/zapx/zap.go)
    95    - usage example: [https://github.com/zeromicro/zero-examples/blob/main/logx/zaplog/main.go](https://github.com/zeromicro/zero-examples/blob/main/logx/zaplog/main.go)
    96  - logrus
    97    - implementation: [https://github.com/zeromicro/zero-contrib/blob/main/logx/logrusx/logrus.go](https://github.com/zeromicro/zero-contrib/blob/main/logx/logrusx/logrus.go)
    98    - usage example: [https://github.com/zeromicro/zero-examples/blob/main/logx/logrus/main.go](https://github.com/zeromicro/zero-examples/blob/main/logx/logrus/main.go)
    99  
   100  For more libs, please implement and PR to [https://github.com/zeromicro/zero-contrib](https://github.com/zeromicro/zero-contrib)
   101  
   102  ## Write the logs to specific stores
   103  
   104  `logx` defined two interfaces to let you customize `logx` to write logs into any stores.
   105  
   106  - `logx.NewWriter(w io.Writer)`
   107  - `logx.SetWriter(writer logx.Writer)`
   108  
   109  For example, if we want to write the logs into kafka instead of console or files, we can do it like below:
   110  
   111  ```go
   112  type KafkaWriter struct {
   113  	Pusher *kq.Pusher
   114  }
   115  
   116  func NewKafkaWriter(pusher *kq.Pusher) *KafkaWriter {
   117  	return &KafkaWriter{
   118  		Pusher: pusher,
   119  	}
   120  }
   121  
   122  func (w *KafkaWriter) Write(p []byte) (n int, err error) {
   123  	// writing log with newlines, trim them.
   124  	if err := w.Pusher.Push(strings.TrimSpace(string(p))); err != nil {
   125  		return 0, err
   126  	}
   127  
   128  	return len(p), nil
   129  }
   130  
   131  func main() {
   132  	pusher := kq.NewPusher([]string{"localhost:9092"}, "go-zero")
   133  	defer pusher.Close()
   134  
   135  	writer := logx.NewWriter(NewKafkaWriter(pusher))
   136  	logx.SetWriter(writer)
   137    
   138  	// more code
   139  }
   140  ```
   141  
   142  Complete code: [https://github.com/zeromicro/zero-examples/blob/main/logx/tokafka/main.go](https://github.com/zeromicro/zero-examples/blob/main/logx/tokafka/main.go)
   143  
   144  ## Filtering sensitive fields
   145  
   146  If we need to prevent the `password` fields from logging, we can do it like below:
   147  
   148  ```go
   149  type (
   150  	Message struct {
   151  		Name     string
   152  		Password string
   153  		Message  string
   154  	}
   155  
   156  	SensitiveLogger struct {
   157  		logx.Writer
   158  	}
   159  )
   160  
   161  func NewSensitiveLogger(writer logx.Writer) *SensitiveLogger {
   162  	return &SensitiveLogger{
   163  		Writer: writer,
   164  	}
   165  }
   166  
   167  func (l *SensitiveLogger) Info(msg interface{}, fields ...logx.LogField) {
   168  	if m, ok := msg.(Message); ok {
   169  		l.Writer.Info(Message{
   170  			Name:     m.Name,
   171  			Password: "******",
   172  			Message:  m.Message,
   173  		}, fields...)
   174  	} else {
   175  		l.Writer.Info(msg, fields...)
   176  	}
   177  }
   178  
   179  func main() {
   180  	// setup logx to make sure originalWriter not nil,
   181  	// the injected writer is only for filtering, like a middleware.
   182  
   183  	originalWriter := logx.Reset()
   184  	writer := NewSensitiveLogger(originalWriter)
   185  	logx.SetWriter(writer)
   186  
   187  	logx.Infov(Message{
   188  		Name:     "foo",
   189  		Password: "shouldNotAppear",
   190  		Message:  "bar",
   191  	})
   192    
   193  	// more code
   194  }
   195  ```
   196  
   197  Complete code: [https://github.com/zeromicro/zero-examples/blob/main/logx/filterfields/main.go](https://github.com/zeromicro/zero-examples/blob/main/logx/filterfields/main.go)
   198  
   199  ## More examples
   200  
   201  [https://github.com/zeromicro/zero-examples/tree/main/logx](https://github.com/zeromicro/zero-examples/tree/main/logx)
   202  
   203  ## Give a Star! ⭐
   204  
   205  If you like or are using this project to learn or start your solution, please give it a star. Thanks!