golang标准库的日志框架很是简单,仅仅提供了print,panic和fatal三个函数。对于更精细的日志级别、日志文件分割,以及日志分发等方面,并无提供支持。在golang的世界,流行的日志框架包括logrus、zap、zerolog、seelog等。github
1. 日志级别: logrus有7个日志级别,依次是Trace << Debug << Info << Warning << Error << Fatal << Panic
golang
// 只输出不低于当前级别是日志数据 logrus.SetLevel(logrus.DebugLevel)
2. 日志格式: logrus内置了JSONFormatter
和TextFormatter
两种格式,也能够经过Formatter
接口定义日志格式redis
// TextFormatter格式 logrus.SetFormatter(&logrus.TextFormatter{ ForceColors: true, EnvironmentOverrideColors: true, TimestampFormat: "2006-01-02 15:04:05", //时间格式 // FullTimestamp:true, // DisableLevelTruncation:true, })
// JSONFormatter格式 logrus.SetFormatter(&logrus.JSONFormatter{ PrettyPrint: false, //格式化 TimestampFormat: "2006-01-02 15:04:05", //时间格式 })
3. 输出文件:api
logfile, _ := os.OpenFile("./app.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644) logrus.SetOutput(logfile) //默认为os.stderr
4. 日志定位: 定位行号(如:func=main.main file="./xxx.go:38"
)安全
logrus.SetReportCaller(true)
示例:并发
func init() { logrus.SetLevel(logrus.DebugLevel) logrus.SetFormatter(&logrus.JSONFormatter{ TimestampFormat: "2006-01-02 15:04:05", }) logfile, _ := os.OpenFile("./app.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644) logrus.SetOutput(logfile) //默认为os.stderr } //方式一:logrus函数(最终调用的是logrus.StandardLogger默认实例方法) func main() { logrus.Infoln("测试数据") }
FieldLogger接口: FieldLogger
定义了全部日志打印的方法app
type FieldLogger interface { WithField(key string, value interface{}) *Entry WithFields(fields Fields) *Entry WithError(err error) *Entry Debugf(format string, args ...interface{}) Infof(format string, args ...interface{}) Printf(format string, args ...interface{}) Warnf(format string, args ...interface{}) Warningf(format string, args ...interface{}) Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Panicf(format string, args ...interface{}) Debug(args ...interface{}) Info(args ...interface{}) Print(args ...interface{}) Warn(args ...interface{}) Warning(args ...interface{}) Error(args ...interface{}) Fatal(args ...interface{}) Panic(args ...interface{}) Debugln(args ...interface{}) Infoln(args ...interface{}) Println(args ...interface{}) Warnln(args ...interface{}) Warningln(args ...interface{}) Errorln(args ...interface{}) Fatalln(args ...interface{}) Panicln(args ...interface{}) }
日志打印1: 默认实例 (函数)
,即经过logrus包提供的函数(覆盖了FieldLogger
接口的全部方法),直接打印日志。但其实logrus包函数是调用了logrus.Loger
默认实例。框架
// 直接调用包函数 func main() { logrus.Infoln("...") logrus.Errorln("...") // ... }
日志打印2:Logger实例(对象)
,它实现了FieldLogger
接口。curl
func main() { //var loger = logrus.StandardLogger() var loger = logrus.New() loger.Formatter = &logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"} loger.Infoln("能够建立任意数量的logrus实例") }
日志打印3:Entry示例(对象)
,它也实现了FieldLogger
接口,是最终是日志打印入口。
Field
机制,logrus鼓励经过Field
机制进行精细化的、结构化的日志记录,而不是经过冗长的消息来记录日志。func main() { logrus.SetFormatter(&logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"}) // Entry实例 entry := logrus.WithFields(logrus.Fields{ "global": "全局字段", }) entry.WithFields(logrus.Fields{"module": "用户模块"}). Info("测试ok") }
logstash
、es
等,或者切割日志、定义日志内容和格式等。hook接口原型以下:type Hook interface { Levels() []Level //日志级别 Fire(*Entry) error //打印入口(Entry对象) }
Hook - 日志切割:
import ( "github.com/lestrrat-go/file-rotatelogs" "github.com/rifflock/lfshook" "github.com/sirupsen/logrus" "time" ) // 说明:按时间切割日志文件(2秒建立一个日志文件) func main() { hook := NewLfsHook("app_hook", time.Second*2, 5) logrus.AddHook(hook) logrus.Infoln("测试开始") log := logrus.WithFields(logrus.Fields{"module": "用户模块"}) for i := 0; i < 10; i++ { log.Infoln("成功", i) time.Sleep(time.Second) } } // 日志钩子(日志拦截,并重定向) func NewLfsHook(logName string, rotationTime time.Duration, leastDay uint) logrus.Hook { writer, err := rotatelogs.New( // 日志文件 logName+".%Y%m%d%H%M%S", // 日志周期(默认每86400秒/一天旋转一次) rotatelogs.WithRotationTime(rotationTime), // 清除历史 (WithMaxAge和WithRotationCount只能选其一) //rotatelogs.WithMaxAge(time.Hour*24*7), //默认每7天清除下日志文件 rotatelogs.WithRotationCount(leastDay), //只保留最近的N个日志文件 ) if err != nil { panic(err) } // 可设置按不一样level建立不一样的文件名 lfsHook := lfshook.NewHook(lfshook.WriterMap{ logrus.DebugLevel: writer, logrus.InfoLevel: writer, logrus.WarnLevel: writer, logrus.ErrorLevel: writer, logrus.FatalLevel: writer, logrus.PanicLevel: writer, }, &logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"}) return lfsHook }
Hook - Redis重定向: 即将日志输出到redis
import ( logredis "github.com/rogierlommers/logrus-redis-hook" "io/ioutil" "github.com/sirupsen/logrus" ) func init() { hookConfig := logredis.HookConfig{ Host: "localhost", Key: "test", Format: "v1", App: "my_app_name", Port: 6379, Hostname: "my_app_hostname", DB: 0, // optional TTL: 3600, } hook, err := logredis.NewHook(hookConfig) if err == nil { logrus.AddHook(hook) } else { logrus.Errorf("logredis error: %q", err) } } func main() { logrus.WithFields(logrus.Fields{ "module": "user"}). Info("user login") // If you want to disable writing to stdout, use setOutput logrus.SetOutput(ioutil.Discard) logrus.Info("log to Redis") } // 测试: // 1.启动redis服务: redis-server // 2.监控redis数据: redis-cli monitor
其余Hook:
MongoDb
:https://github.com/weekface/mgorusRedis
:https://github.com/rogierlommers/logrus-redis-hookInfluxDb
:https://github.com/abramovic/logrus_influxdbLogstash
:https://github.com/bshuster-repo/logrus-logstash-hookfunc init() { // 输出格式 logrus.SetFormatter(&logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"}) // 输出路径 logfile, _ := os.OpenFile("./app.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644) logrus.SetOutput(logfile) // Gin日志重定向 gin.DisableConsoleColor() //不须要颜色 gin.DefaultWriter = io.MultiWriter(os.Stdout, logfile) //os.Stdout } //测试:curl 0.0.0.0:8080/index func main() { log := logrus.WithFields(logrus.Fields{ "module": "用户模块", }) r := gin.Default() r.GET("/index", func(c *gin.Context) { log.Warnln("gin日志数据") c.String(200, "ok") }) _ = r.Run() }
Fatal
输出,会执行os.Exit(1)
。logrus提供RegisterExitHandler
方法,能够在系统异常时调用一些资源释放api等,让应用正确地关闭。func main() { logrus.RegisterExitHandler(func() { fmt.Println("发生了fatal异常,执行关闭文件等工做") }) logrus.Warnln("warn测试") logrus.Fatalln("fatal测试") logrus.Infoln("info测试") //不会执行 }
logger.SetNoLock()
来关闭之。参考