logreduction.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package logreduction
  14. import (
  15. "sync"
  16. "time"
  17. )
  18. var nowfunc = func() time.Time { return time.Now() }
  19. // LogReduction provides a filter for consecutive identical log messages;
  20. // a message will be printed no more than once per interval.
  21. // If a string of messages is interrupted by a different message,
  22. // the interval timer will be reset.
  23. type LogReduction struct {
  24. lastError map[string]string
  25. errorPrinted map[string]time.Time
  26. errorMapLock sync.Mutex
  27. identicalErrorDelay time.Duration
  28. }
  29. // NewLogReduction returns an initialized LogReduction
  30. func NewLogReduction(identicalErrorDelay time.Duration) *LogReduction {
  31. l := new(LogReduction)
  32. l.lastError = make(map[string]string)
  33. l.errorPrinted = make(map[string]time.Time)
  34. l.identicalErrorDelay = identicalErrorDelay
  35. return l
  36. }
  37. func (l *LogReduction) cleanupErrorTimeouts() {
  38. for name, timeout := range l.errorPrinted {
  39. if nowfunc().Sub(timeout) >= l.identicalErrorDelay {
  40. delete(l.errorPrinted, name)
  41. delete(l.lastError, name)
  42. }
  43. }
  44. }
  45. // ShouldMessageBePrinted determines whether a message should be printed based
  46. // on how long ago this particular message was last printed
  47. func (l *LogReduction) ShouldMessageBePrinted(message string, parentID string) bool {
  48. l.errorMapLock.Lock()
  49. defer l.errorMapLock.Unlock()
  50. l.cleanupErrorTimeouts()
  51. lastMsg, ok := l.lastError[parentID]
  52. lastPrinted, ok1 := l.errorPrinted[parentID]
  53. if !ok || !ok1 || message != lastMsg || nowfunc().Sub(lastPrinted) >= l.identicalErrorDelay {
  54. l.errorPrinted[parentID] = nowfunc()
  55. l.lastError[parentID] = message
  56. return true
  57. }
  58. return false
  59. }
  60. // ClearID clears out log reduction records pertaining to a particular parent
  61. // (e. g. container ID)
  62. func (l *LogReduction) ClearID(parentID string) {
  63. l.errorMapLock.Lock()
  64. defer l.errorMapLock.Unlock()
  65. delete(l.lastError, parentID)
  66. delete(l.errorPrinted, parentID)
  67. }