SoFunction
Updated on 2025-03-05

Go implements integrated Logrus to implement log printing

Github:/sirupsen/lo…

1 Initial use

package main
import (
   "context"
   "/sirupsen/logrus"
)
​
func main() {
   method0()
}
func method0() {
   logger:= ()
   ("This is a first log.")
   ctx := ((),"key","value")
   (ctx,"This is a second log.")
}

2 Add tags withFields

package main​
import (
   "context"
   "/sirupsen/logrus"
)
func main() {
   method1()
}
func method1() {
   ({
      "fieldKey": "fieldValue",
   }).Warning("This is a first field log.")
​
   ({
      "fieldKey": "fieldValue",
      "fieldKey2": "fieldValue2",
   }).Warning("This is a second field log.")
}

3 Configure common parameters

package main
import (
   "context"
   "/sirupsen/logrus"
   log "/sirupsen/logrus"
   "os"
)
​func main() {
   method2()
}
func init() {
   // Logs are used as JSON instead of the default ASCII formatter.   (&{})
​
   // Output to standard output, can be any   ()
​
   // Only logs at xx level or above   ()
}
func method2() {
   ({
      "animal": "walrus",
      "size":   10,
   }).Info("A group of walrus emerges from the ocean")
​
   ({
      "omg":    true,
      "number": 122,
   }).Warn("The group's number increased tremendously!")
​
   ({
      "omg":    true,
      "number": 100,
   }).Fatal("The ice breaks!")
}

Formatter is generally divided into two types:

  • &{}
  • &{}

There are seven log levels:

  • ()
  • ()
  • ()
  • ()
  • ()
  • ()
  • ()

4 Output log to file

package main
import (
    "context"
    "/sirupsen/logrus"
    "os"
)
func main() {
    method4()
}
func method4() {
   var log = ()
   file ,err := ("", os.O_CREATE|os.O_WRONLY, 0666)
   if err == nil{
       = file
   }else{
      ("Failed to log to file")
   }
​
   ({
      "filename": "",
   }).Info("This is a file log")
}

Contents of the file:

time="2022-01-06T13:04:25+08:00" level=info msg="This is a file log" filename=\

5 Use Hooks to output logs to other places

import (
  log "/sirupsen/logrus"
  "/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake"
  logrus_syslog "/sirupsen/logrus/hooks/syslog"
  "log/syslog"
)
func init() {
  // Use the airlock hook to report error severity or above an exception tracking.  You can create custom hooks, see the Hooks section.  ((123, "xyz", "production"))
​
  hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
  if err != nil {
    ("Unable to connect to local syslog daemon")
  } else {
    (hook)
  }
}

Just add the corresponding Hook to AddHook

This is the article about Go implementing the integration of Logrus log printing. For more information about Go Logrus log printing, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!