// 创建一个新的logger实例。可以创建任意多个。 var log = logrus.New()
funcmain() { log.Trace("Something very low level.") log.Debug("Useful debugging information.") log.Info("Something noteworthy happened!") log.Warn("You should probably take a look at this.") log.Error("Something failed but I'm not quitting.") // 记完日志后会调用os.Exit(1) log.Fatal("Bye.") // 记完日志后会调用 panic() log.Panic("I'm bailing.") } /* INFO[0000] Something noteworthy happened! WARN[0000] You should probably take a look at this. ERRO[0000] Something failed but I'm not quitting. FATA[0000] Bye. */
funcmain() { requestLogger := log.WithFields(log.Fields{"request_id": "request_id", "user_ip": "user_ip"}) requestLogger.Info("something happened on that request") // will log request_id and user_ip requestLogger.Warn("something not great happened") } /* INFO[0000] something happened on that request request_id=request_id user_ip=user_ip WARN[0000] something not great happened request_id=request_id user_ip=user_ip */
package main import ( log "github.com/sirupsen/logrus" "gopkg.in/gemnasium/logrus-airbrake-hook.v2"// the package is named "airbrake" logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" "log/syslog" )
funcinit() {
// Use the Airbrake hook to report errors that have Error severity or above to // an exception tracker. You can create custom hooks, see the Hooks section. log.AddHook(airbrake.NewHook(123, "xyz", "production"))
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") if err != nil { log.Error("Unable to connect to local syslog daemon") } else { log.AddHook(hook) } }
funcinit() { // Log as JSON instead of the default ASCII formatter. log.Formatter = &logrus.JSONFormatter{} // Output to stdout instead of the default stderr // Can be any io.Writer, see below for File example f, _ := os.Create("./gin.log") log.Out = f gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = log.Out // Only log the warning severity or above. log.Level = logrus.InfoLevel }
funcmain() { // 创建一个默认的路由引擎 r := gin.Default() // GET:请求方式;/hello:请求的路径 // 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数 r.GET("/hello", func(c *gin.Context) { log.WithFields(logrus.Fields{ "animal": "walrus", "size": 10, }).Warn("A group of walrus emerges from the ocean") // c.JSON:返回JSON格式的数据 c.JSON(200, gin.H{ "message": "Hello world!", }) }) // 启动HTTP服务,默认在0.0.0.0:8080启动服务 fmt.Println(`http://127.0.0.1:8080/hello`) r.Run(":8080") }
记录日志
1 2
{"animal":"walrus","level":"warning","msg":"A group of walrus emerges from the ocean","size":10,"time":"2021-12-23T12:37:21+08:00"} [GIN] 2021/12/23 - 12:37:21 | 200 | 705.823µs | 127.0.0.1 | GET "/hello"