logrus.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package log
  2. import (
  3. "context"
  4. "io/ioutil"
  5. "os"
  6. "github.com/sirupsen/logrus"
  7. )
  8. func init() {
  9. redirectLogrus()
  10. }
  11. func redirectLogrus() {
  12. // FIXME: because of different stack depth call runtime.Caller will get error function name.
  13. logrus.AddHook(redirectHook{})
  14. if os.Getenv("LOGRUS_STDOUT") == "" {
  15. logrus.SetOutput(ioutil.Discard)
  16. }
  17. }
  18. type redirectHook struct{}
  19. func (redirectHook) Levels() []logrus.Level {
  20. return logrus.AllLevels
  21. }
  22. func (redirectHook) Fire(entry *logrus.Entry) error {
  23. lv := _infoLevel
  24. var logrusLv string
  25. var verbose int32
  26. switch entry.Level {
  27. case logrus.FatalLevel, logrus.PanicLevel:
  28. logrusLv = entry.Level.String()
  29. fallthrough
  30. case logrus.ErrorLevel:
  31. lv = _errorLevel
  32. case logrus.WarnLevel:
  33. lv = _warnLevel
  34. case logrus.InfoLevel:
  35. lv = _infoLevel
  36. case logrus.DebugLevel:
  37. // use verbose log replace of debuglevel
  38. verbose = 10
  39. }
  40. args := make([]D, 0, len(entry.Data)+1)
  41. args = append(args, D{Key: _log, Value: entry.Message})
  42. for k, v := range entry.Data {
  43. args = append(args, D{Key: k, Value: v})
  44. }
  45. if logrusLv != "" {
  46. args = append(args, D{Key: "logrus_lv", Value: logrusLv})
  47. }
  48. if verbose != 0 {
  49. V(verbose).Infov(context.Background(), args...)
  50. } else {
  51. h.Log(context.Background(), lv, args...)
  52. }
  53. return nil
  54. }