You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

example_basic_test.go 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package logrus_test
  2. import (
  3. "os"
  4. "github.com/sirupsen/logrus"
  5. )
  6. func Example_basic() {
  7. var log = logrus.New()
  8. log.Formatter = new(logrus.JSONFormatter)
  9. log.Formatter = new(logrus.TextFormatter) //default
  10. log.Formatter.(*logrus.TextFormatter).DisableColors = true // remove colors
  11. log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output
  12. log.Level = logrus.TraceLevel
  13. log.Out = os.Stdout
  14. // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
  15. // if err == nil {
  16. // log.Out = file
  17. // } else {
  18. // log.Info("Failed to log to file, using default stderr")
  19. // }
  20. defer func() {
  21. err := recover()
  22. if err != nil {
  23. entry := err.(*logrus.Entry)
  24. log.WithFields(logrus.Fields{
  25. "omg": true,
  26. "err_animal": entry.Data["animal"],
  27. "err_size": entry.Data["size"],
  28. "err_level": entry.Level,
  29. "err_message": entry.Message,
  30. "number": 100,
  31. }).Error("The ice breaks!") // or use Fatal() to force the process to exit with a nonzero code
  32. }
  33. }()
  34. log.WithFields(logrus.Fields{
  35. "animal": "walrus",
  36. "number": 0,
  37. }).Trace("Went to the beach")
  38. log.WithFields(logrus.Fields{
  39. "animal": "walrus",
  40. "number": 8,
  41. }).Debug("Started observing beach")
  42. log.WithFields(logrus.Fields{
  43. "animal": "walrus",
  44. "size": 10,
  45. }).Info("A group of walrus emerges from the ocean")
  46. log.WithFields(logrus.Fields{
  47. "omg": true,
  48. "number": 122,
  49. }).Warn("The group's number increased tremendously!")
  50. log.WithFields(logrus.Fields{
  51. "temperature": -4,
  52. }).Debug("Temperature changes")
  53. log.WithFields(logrus.Fields{
  54. "animal": "orca",
  55. "size": 9009,
  56. }).Panic("It's over 9000!")
  57. // Output:
  58. // level=trace msg="Went to the beach" animal=walrus number=0
  59. // level=debug msg="Started observing beach" animal=walrus number=8
  60. // level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
  61. // level=warning msg="The group's number increased tremendously!" number=122 omg=true
  62. // level=debug msg="Temperature changes" temperature=-4
  63. // level=panic msg="It's over 9000!" animal=orca size=9009
  64. // level=error msg="The ice breaks!" err_animal=orca err_level=panic err_message="It's over 9000!" err_size=9009 number=100 omg=true
  65. }