logx

[!TIP] This document is machine-translated by Google. If you find grammatical and semantic errors, and the document description is not clear, please PR

Example

  1. var c logx.LogConf
  2. // Initialize the configuration from the yaml file
  3. conf.MustLoad("config.yaml", &c)
  4. // logx is initialized according to the configuration
  5. logx.MustSetup(c)
  6. logx.Info("This is info!")
  7. logx.Infof("This is %s!", "info")
  8. logx.Error("This is error!")
  9. logx.Errorf("this is %s!", "error")
  10. logx.Close()

Initialization

logx has many configurable items, you can refer to the definition in logx.LogConf. Currently available

  1. logx.MustSetUp(c)

Perform the initial configuration. If the initial configuration is not performed, all the configurations will use the default configuration.

Level

The print log levels supported by logx are:

  • info
  • error
  • server
  • fatal
  • slow
  • stat

You can use the corresponding method to print out the log of the corresponding level. At the same time, in order to facilitate debugging and online use, the log printing level can be dynamically adjusted. The level can be set through logx.SetLevel(uint32) or through configuration initialization. The currently supported parameters are:

  1. const (
  2. // Print all levels of logs
  3. InfoLevel = iotas
  4. // Print errors, slows, stacks logs
  5. ErrorLevel
  6. // Only print server level logs
  7. SevereLevel
  8. )

Log mode

At present, the log printing mode is mainly divided into two types, one is file output, and the other is console output. The recommended way, when using k8s, docker and other deployment methods, you can output the log to the console, use the log collector to collect and import it to es for log analysis. If it is a direct deployment method, the file output method can be used, and logx will automatically create log files corresponding to 5 corresponding levels in the specified file directory to save the logs.

  1. .
  2. ├── access.log
  3. ├── error.log
  4. ├── severe.log
  5. ├── slow.log
  6. └── stat.log

At the same time, the file will be divided according to the natural day. When the specified number of days is exceeded, the log file will be automatically deleted, packaged and other operations.

Disable log

If you don’t need log printing, you can use logx.Close() to close the log output. Note that when log output is disabled, it cannot be opened again. For details, please refer to the implementation of logx.RotateLogger and logx.DailyRotateRule.

Close log

Because logx uses asynchronous log output, if the log is not closed normally, some logs may be lost. The log output must be turned off where the program exits:

  1. logx.Close()

Log configuration and shutdown related operations have already been done in most places such as rest and zrpc in the framework, so users don’t need to care. At the same time, note that when the log output is turned off, the log cannot be printed again.

Recommended writing:

  1. import "github.com/tal-tech/go-zero/core/proc"
  2. // grace close log
  3. proc.AddShutdownListener(func() {
  4. logx.Close()
  5. })

Duration

When we print the log, we may need to print the time-consuming situation, we can use logx.WithDuration(time.Duration), refer to the following example:

  1. startTime := timex.Now()
  2. // Database query
  3. rows, err := conn.Query(q, args...)
  4. duration := timex.Since(startTime)
  5. if duration > slowThreshold {
  6. logx.WithDuration(duration).Slowf("[SQL] query: slowcall - %s", stmt)
  7. } else {
  8. logx.WithDuration(duration).Infof("sql query: %s", stmt)
  9. }

Will output the following format:

  1. {"@timestamp":"2020-09-12T01:22:55.552+08","level":"info","duration":"3.0ms","content":"sql query:..."}
  2. {"@timestamp":"2020-09-12T01:22:55.552+08","level":"slow","duration":"500ms","content":"[SQL] query: slowcall - ..."}

In this way, it is easy to collect statistics about slow sql related information.

TraceLog

tracingEntry is customized for link tracing log output. You can print the traceId and spanId information in the context. With our rest and zrpc, it is easy to complete the related printing of the link log. The example is as follows:

  1. logx.WithContext(context.Context).Info("This is info!")

SysLog

Some applications may use system log for log printing. Logx uses the same encapsulation method, which makes it easy to collect log-related logs into logx.

  1. logx.CollectSysLog()

Log configuration related

LogConf Define the basic configuration required for the logging system

The complete definition is as follows:

  1. type LogConf struct {
  2. ServiceName string `json:",optional"`
  3. Mode string `json:",default=console,options=console|file|volume"`
  4. Path string `json:",default=logs"`
  5. Level string `json:",default=info,options=info|error|severe"`
  6. Compress bool `json:",optional"`
  7. KeepDays int `json:",optional"`
  8. StackCooldownMillis int `json:",default=100"`
  9. }

Mode

Mode defines the log printing method. The default mode is console, which will print to the console.

The currently supported modes are as follows:

  • console
    • Print to the console
  • file
    • Print to access.log, error.log, stat.log and other files in the specified path
  • volume
    • In order to print to the storage that the mount comes in in k8s, because multiple pods may overwrite the same file, the volume mode automatically recognizes the pod and writes separate log files according to the pod.

Path

Path defines the output path of the file log, the default value is logs.

Level

Level defines the log printing level, and the default value is info. The currently supported levels are as follows:

  • info
  • error
  • severe

Compress

Compress defines whether the log needs to be compressed, the default value is false. When Mode is file mode, the file will finally be packaged and compressed into a .gz file.

KeepDays

KeepDays defines the maximum number of days to keep logs. The default value is 0, which means that old logs will not be deleted. When Mode is file mode, if the maximum retention days are exceeded, the old log files will be deleted.

StackCooldownMillis

StackCooldownMillis defines the log output interval, the default is 100 milliseconds.