This is a creation in Article, where the information may have evolved or changed.
Golang has a simple feature of the log frame, only the print, panic, fatal three methods, for general log cutting and other functions do not provide support.
It is recommended to use the Sirupsen/logrus log library.
Logrus feature
- Structured and pluggable log modules
- Fully compatible with official Log library interface
- Field mechanism
- Extensible Hook Mechanism
- Text and JSON two alternative formats
Simple Use Example
STD Logger
Similar to the official log, Logrus also provides a standard logger called STD, which can be used as a way to use STD logging directly using the various methods exported externally.
package mainimport log "github.com/sirupsen/logrus"func main() { log.Info("hello, world.")}
Self-built logger instances
package mainimport ( "os" "github.com/sirupsen/logrus")// Create a new instance of the logger. You can have any number of instances.var log = logrus.New()func main() { // The API for setting attributes is a little different than the package level // exported logger. See Godoc. log.Out = os.Stdout // You could set this to any `io.Writer` such as a file // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) // if err == nil { // log.Out = file // } else { // log.Info("Failed to log to file, using default stderr") // } log.WithFields(logrus.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean")}
Output to local file system
The following example code outputs a log to a local file system via a hook, and provides log cutting capabilities
Import ("Github.com/lestrrat/go-file-rotatelogs" "Github.com/rifflock/lfshook" Log "Github.com/sirupsen/logrus" "Time" "OS" "Github.com/pkg/errors" "path"//config Logrus log to local filesystem, with file Rotationfunc Co Nfiglocalfilesystemlogger (LogPath string, logfilename string, MaxAge time. Duration, Rotationtime time. Duration) {baselogpaht: = path. Join (LogPath, LogFileName) writer, err: = Rotatelogs. New (baselogpaht+ ".%y%m%d%h%m", Rotatelogs. Withlinkname (BASELOGPAHT),//Generate a soft chain, point to the latest log file rotatelogs. Withmaxage (MaxAge),//File maximum save time rotatelogs. Withrotationtime (Rotationtime),//Log cut time interval) if err! = Nil {log. Errorf ("config local file system logger error. %+v ", errors. Withstack (Err)} Lfhook: = Lfshook. Newhook (Lfshook. writermap{log. Debuglevel:writer,//Set different output destination for different levels Log.InfoLevel:writer, log. Warnlevel:writer, log. Errorlevel:writer, log. Fatallevel:writer, log. PaNiclevel:writer,}) log. Addhook (Lfhook)}
Output to MQ or ES
The following example code prints the logs to the AMQP message queue, or ES, via hooks.
Import ("Github.com/vladoatanasov/logrus_amqp" "Gopkg.in/olivere/elastic.v5" "Gopkg.in/sohlich/elogru S.v2 "Log" Github.com/sirupsen/logrus "" github.com/pkg/errors ")//config Logrus log to Amqpfunc Configamqplogger (ser ver, username, password, exchange, ExchangeType, VirtualHost, routingkey string) {hook: = logrus_amqp. Newamqphookwithtype (server, username, password, exchange, ExchangeType, VirtualHost, Routingkey) log. Addhook (Hook)}//config Logrus log to Esfunc Configeslogger (Esurl string, eshost string, index String) {client, err: = Elastic. Newclient (elastic. SetUrl (Esurl)) if err! = Nil {log. Errorf ("Config es logger error. %+v ", errors. Withstack (Err)} Eshook, err: = Elogrus. Newelastichook (client, eshost, log. DebugLevel, index) if err! = Nil {log. Errorf ("Config es logger error. %+v ", errors. Withstack (ERR))} log. Addhook (Eshook)}