Logging with Go

Keywords: Go JSON

brief introduction

In the previous section, we used viper to read the configuration file.

logrus is used to log in this section.

logrus is a structured logger with fully compatible API s with logger in standard libraries.

Define configuration

First, update the configuration file and add the following parameters:

log:
  use_json: true
  logger_level: debug
  logger_file: log/server.log
  gin_file: log/gin.log
  gin_console: true

logrus supports logging in JSON format:

logrus.SetFormatter(&log.JSONFormatter{})

The second and third parameters set the log record level and the log save path.
The last two parameters are gin's log settings.

Read log-related configuration

// Initialization log
func (c *Config) InitLog() {
    // log.use_json
    if viper.GetBool("log.use_json") {
        logrus.SetFormatter(&logrus.JSONFormatter{})
    }

    // log.logger_level
    switch viper.GetString("log.logger_level") {
    case "trace":
        logrus.SetLevel(logrus.TraceLevel)
    case "debug":
        logrus.SetLevel(logrus.DebugLevel)
    case "info":
        logrus.SetLevel(logrus.InfoLevel)
    case "warn":
        logrus.SetLevel(logrus.WarnLevel)
    case "error":
        logrus.SetLevel(logrus.ErrorLevel)
    }

    // log.logger_file
    logger_file := viper.GetString("log.logger_file")
    os.MkdirAll(filepath.Dir(logger_file), os.ModePerm)

    file, err := os.OpenFile(logger_file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
    if err == nil {
        logrus.SetOutput(file)
    }

    // log.gin_file & log.gin_console
    gin_file := viper.GetString("log.gin_file")
    os.MkdirAll(filepath.Dir(gin_file), os.ModePerm)

    file, err = os.OpenFile(gin_file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
    if err == nil {
        if viper.GetBool("log.gin_console") {
            gin.DefaultWriter = io.MultiWriter(file, os.Stdout)
        } else {
            gin.DefaultWriter = io.MultiWriter(file)
        }
    }

    // default
    logrus.SetReportCaller(true)
}

This method reads the log-related configuration parameters and then calls the corresponding method.

So where do I call this method?

At present, I call it in initConfig, which makes the log configuration fixed at initialization.
Therefore, the log-related configuration is not affected when the configuration file is adjusted.

If you need to update the log configuration in real time, you can consider putting it in runServer.

summary

Unlike the original author, I did not consider log compression and dump.

Another point is that there is no uniform processing of gin's logs, and decentralized processing is chosen.

The current part of the code

As version v0.3.0

Posted by thegman on Thu, 03 Oct 2019 11:16:09 -0700