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.

97 lines
2.3 KiB

8 years ago
8 years ago
8 years ago
  1. package log
  2. // NewFilter wraps next and implements filtering. See the commentary on the
  3. // Option functions for a detailed description of how to configure levels. If
  4. // no options are provided, all leveled log events created with Debug, Info or
  5. // Error helper methods are squelched.
  6. func NewFilter(next Logger, options ...Option) Logger {
  7. l := &filter{
  8. next: next,
  9. }
  10. for _, option := range options {
  11. option(l)
  12. }
  13. return l
  14. }
  15. type filter struct {
  16. next Logger
  17. allowed level
  18. errNotAllowed error
  19. }
  20. func (l *filter) Info(msg string, keyvals ...interface{}) error {
  21. levelAllowed := l.allowed&levelInfo != 0
  22. if !levelAllowed {
  23. return l.errNotAllowed
  24. }
  25. return l.next.Info(msg, keyvals...)
  26. }
  27. func (l *filter) Debug(msg string, keyvals ...interface{}) error {
  28. levelAllowed := l.allowed&levelDebug != 0
  29. if !levelAllowed {
  30. return l.errNotAllowed
  31. }
  32. return l.next.Debug(msg, keyvals...)
  33. }
  34. func (l *filter) Error(msg string, keyvals ...interface{}) error {
  35. levelAllowed := l.allowed&levelError != 0
  36. if !levelAllowed {
  37. return l.errNotAllowed
  38. }
  39. return l.next.Error(msg, keyvals...)
  40. }
  41. func (l *filter) With(keyvals ...interface{}) Logger {
  42. return l.next.With(keyvals...)
  43. }
  44. // Option sets a parameter for the filter.
  45. type Option func(*filter)
  46. // AllowAll is an alias for AllowDebug.
  47. func AllowAll() Option {
  48. return AllowDebug()
  49. }
  50. // AllowDebug allows error, info and debug level log events to pass.
  51. func AllowDebug() Option {
  52. return allowed(levelError | levelInfo | levelDebug)
  53. }
  54. // AllowInfo allows error and info level log events to pass.
  55. func AllowInfo() Option {
  56. return allowed(levelError | levelInfo)
  57. }
  58. // AllowError allows only error level log events to pass.
  59. func AllowError() Option {
  60. return allowed(levelError)
  61. }
  62. // AllowNone allows no leveled log events to pass.
  63. func AllowNone() Option {
  64. return allowed(0)
  65. }
  66. func allowed(allowed level) Option {
  67. return func(l *filter) { l.allowed = allowed }
  68. }
  69. // ErrNotAllowed sets the error to return from Log when it squelches a log
  70. // event disallowed by the configured Allow[Level] option. By default,
  71. // ErrNotAllowed is nil; in this case the log event is squelched with no
  72. // error.
  73. func ErrNotAllowed(err error) Option {
  74. return func(l *filter) { l.errNotAllowed = err }
  75. }
  76. type level byte
  77. const (
  78. levelDebug level = 1 << iota
  79. levelInfo
  80. levelError
  81. )