- Introduction to the
- Define the configuration
- Read log related configurations
- conclusion
- Code for the current section
Introduction to the
In the previous section, we used Viper to read the configuration file.
This section uses Logrus for logging.
Logrus is a structured logger with a fully compatible API with the standard library loggers.
Define the configuration
First, update the configuration file to add the following parameters:
log:
use_json: true
logger_level: debug
logger_file: log/server.log
gin_file: log/gin.log
gin_console: true
Copy the code
Logrus supports logging in JSON format:
logrus.SetFormatter(&log.JSONFormatter{})
Copy the code
The second and third parameters set the log level and log saving path, and the last two parameters are gin’s log setting parameters.
Read log related configurations
// Initialize the log
func (c *Config) InitLog(a) {
// 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)}Copy the code
This method reads the log-related configuration parameters and then calls the corresponding methods.
So where do I call this method?
Currently I call it in initConfig, which makes the log configuration fixed at initialization, so when adjusting the configuration file it doesn’t affect the log related configuration.
If you need to update the logging configuration in real time, consider running Server.
conclusion
Unlike the original author, I do not consider compression and dump of logs.
Another point is that there is no uniform processing of GIN’s logs, and the alternative is decentralized processing.
Code for the current section
As version V0.3.0