2
0

log.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package log
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // Logger interface used as base logger throughout the library.
  7. type Logger interface {
  8. Print(args ...interface{})
  9. Printf(format string, args ...interface{})
  10. Trace(args ...interface{})
  11. Tracef(format string, args ...interface{})
  12. Debug(args ...interface{})
  13. Debugf(format string, args ...interface{})
  14. Info(args ...interface{})
  15. Infof(format string, args ...interface{})
  16. Warn(args ...interface{})
  17. Warnf(format string, args ...interface{})
  18. Error(args ...interface{})
  19. Errorf(format string, args ...interface{})
  20. Fatal(args ...interface{})
  21. Fatalf(format string, args ...interface{})
  22. Panic(args ...interface{})
  23. Panicf(format string, args ...interface{})
  24. WithPrefix(prefix string) Logger
  25. Prefix() string
  26. WithFields(fields Fields) Logger
  27. Fields() Fields
  28. SetLevel(level Level)
  29. }
  30. type Loggable interface {
  31. Log() Logger
  32. }
  33. type Fields map[string]interface{}
  34. func (fields Fields) String() string {
  35. str := make([]string, 0)
  36. for k, v := range fields {
  37. str = append(str, fmt.Sprintf("%s=%+v", k, v))
  38. }
  39. return strings.Join(str, " ")
  40. }
  41. func (fields Fields) WithFields(newFields Fields) Fields {
  42. allFields := make(Fields)
  43. for k, v := range fields {
  44. allFields[k] = v
  45. }
  46. for k, v := range newFields {
  47. allFields[k] = v
  48. }
  49. return allFields
  50. }
  51. func AddFieldsFrom(logger Logger, values ...interface{}) Logger {
  52. for _, value := range values {
  53. switch v := value.(type) {
  54. case Logger:
  55. logger = logger.WithFields(v.Fields())
  56. case Loggable:
  57. logger = logger.WithFields(v.Log().Fields())
  58. case interface{ Fields() Fields }:
  59. logger = logger.WithFields(v.Fields())
  60. }
  61. }
  62. return logger
  63. }