logger.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package nebula
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "github.com/sirupsen/logrus"
  8. "github.com/slackhq/nebula/config"
  9. )
  10. type ContextualError struct {
  11. RealError error
  12. Fields map[string]interface{}
  13. Context string
  14. }
  15. func NewContextualError(msg string, fields map[string]interface{}, realError error) ContextualError {
  16. return ContextualError{Context: msg, Fields: fields, RealError: realError}
  17. }
  18. func (ce ContextualError) Error() string {
  19. if ce.RealError == nil {
  20. return ce.Context
  21. }
  22. return ce.RealError.Error()
  23. }
  24. func (ce ContextualError) Unwrap() error {
  25. if ce.RealError == nil {
  26. return errors.New(ce.Context)
  27. }
  28. return ce.RealError
  29. }
  30. func (ce *ContextualError) Log(lr *logrus.Logger) {
  31. if ce.RealError != nil {
  32. lr.WithFields(ce.Fields).WithError(ce.RealError).Error(ce.Context)
  33. } else {
  34. lr.WithFields(ce.Fields).Error(ce.Context)
  35. }
  36. }
  37. func configLogger(l *logrus.Logger, c *config.C) error {
  38. // set up our logging level
  39. logLevel, err := logrus.ParseLevel(strings.ToLower(c.GetString("logging.level", "info")))
  40. if err != nil {
  41. return fmt.Errorf("%s; possible levels: %s", err, logrus.AllLevels)
  42. }
  43. l.SetLevel(logLevel)
  44. disableTimestamp := c.GetBool("logging.disable_timestamp", false)
  45. timestampFormat := c.GetString("logging.timestamp_format", "")
  46. fullTimestamp := (timestampFormat != "")
  47. if timestampFormat == "" {
  48. timestampFormat = time.RFC3339
  49. }
  50. logFormat := strings.ToLower(c.GetString("logging.format", "text"))
  51. switch logFormat {
  52. case "text":
  53. l.Formatter = &logrus.TextFormatter{
  54. TimestampFormat: timestampFormat,
  55. FullTimestamp: fullTimestamp,
  56. DisableTimestamp: disableTimestamp,
  57. }
  58. case "json":
  59. l.Formatter = &logrus.JSONFormatter{
  60. TimestampFormat: timestampFormat,
  61. DisableTimestamp: disableTimestamp,
  62. }
  63. default:
  64. return fmt.Errorf("unknown log format `%s`. possible formats: %s", logFormat, []string{"text", "json"})
  65. }
  66. return nil
  67. }