一、安装
github.com/sirupsen/logrus
logrus使用配置文件
{
"log_path":"logs",
"log_name":"gin_project.log",
"log_level":"info"
}
二、加载配置
package logs_source
import (
"os"
"io/ioutil"
"fmt"
"encoding/json"
)
type LogConfig struct {
LogPath string `json:"log_path"`
LogName string `json:"log_name"`
LogLevel string `json:"log_level"`
}
func LoadLogConfig() *LogConfig{
log_conf := LogConfig{}
file,err := os.Open("conf/log_conf.json")
if err != nil {
panic(err)
}
defer file.Close()
byte_datas,err2 := ioutil.ReadAll(file)
if err2 != nil {
panic(err2)
}
err3 := json.Unmarshal(byte_datas,&log_conf)
if err3 != nil {
fmt.Println(err3)
}
fmt.Println(log_conf)
return &log_conf
}
三、初始化
package logs_source
import (
"github.com/sirupsen/logrus"
"os"
"fmt"
)
// 创建一个实例
var Log = logrus.New()
func init() {
log_conf := LoadLogConfig()
// 设置日志输出文件
log_dir := log_conf.LogPath + "/" +log_conf.LogName
fmt.Println(log_dir)
file,err := os.OpenFile(log_dir,os.O_APPEND|os.O_WRONLY,os.ModeAppend)
if err != nil {
panic(err)
}
Log.Out = file
// 设置日志級別
level_mapping := map[string]logrus.Level{
"trace":logrus.TraceLevel,
"debug":logrus.DebugLevel,
"info":logrus.InfoLevel,
"warn":logrus.WarnLevel,
"error":logrus.ErrorLevel,
"fatal":logrus.FatalLevel,
"panic":logrus.PanicLevel,
}
Log.SetLevel(level_mapping[log_conf.LogLevel])
// 日志格式化
Log.SetFormatter(&logrus.TextFormatter{})
}
//func main() {
// Log.Info("xxxxx")
//}
logs.Log.Warn("这是一个warnning级别的日志")
logs.Log.WithFields(logrus.Fields{
"msg": "测试的错误",
}).Warn("这是一个warnning级别的日志")